开发者

Regex test and store result in javascript

开发者 https://www.devze.com 2023-01-21 05:35 出处:网络
开发者_运维知识库In ruby, I often use something like this: if \"my string123\" =~ /string(\\d+)/

开发者_运维知识库In ruby, I often use something like this:

if "my string123" =~ /string(\d+)/
  puts "I got #{$1}"
end

How would I do something similar in javascript? Currently, I've been doing this but it feels dirty.

m = "my string123".match(/string(\d+)/)
if (m)
  puts "I got " + m[1]

Perhaps I should just live with this, but thought I'd ask if there was a syntax subtelty I was missing. Thanks!


You aren't missing anything.
If m is already defined, you could do if(m = "string".match(/regex/)), but this is less clean anyway, and you cannot use that with var.


this is just for testing the appearance of the expression in the text:


    var a = "my string123"; //or given as data..
    var b = /string(\d+)/;
    if (b.test(a)) alert("found some digits inside");

this is for getting an array of matches:


var str = "Watch out for the rock!".match(/r?or?/g);

str then contains ["o","or","ro"]

0

精彩评论

暂无评论...
验证码 换一张
取 消