简体   繁体   中英

Regex - match any digit in a string

I have the following Javascript

function myFunction() {
    var str = "depth10 shown"; 
    var depth= str.match(/^depth[\d+$]/);
    console.log(depth);
}

My function is trying to find if depth* is present in the string, where * is always numeric (ex: depth0, depth1, depth100) and return the numeric value in it. In the example above, depth is always returning only one digit instead of all digits. Can anyone explain why?

You're improperly utilizing a character class, you want to use a capturing group instead:

var str = 'depth10 shown or depth100 and depth1'
var re  = /depth(\d+)/gi, 
matches = [];

while (m = re.exec(str)) {
  matches.push(m[1]);
}
console.log(matches) //=> [ '10', '100', '1' ]

Note: If you will have more than 1 "depth*" substrings in your string, you'll want to use the exec() method in a loop pushing the match result of the captured group to the results array.

Otherwise, you can use the match method here:

var r = 'depth10 shown'.match(/depth(\d+)/)
if (r)
    console.log(r[1]); //=> "10"

$ Matches end of input. ie. /t$/ does not match the 't' in "eater", but does match it in "eat".

^ Matches beginning of input. ie, /^A/ does not match the 'A' in "an A", but does match the 'A' in "An E".

Try:

var str = "depth10 shown".match(/depth\d+/gi);
console.log(str[0])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM