1

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?

2
  • [\d+$] will match a digit or plus or $ Commented Jun 9, 2015 at 19:31
  • Paste your regex - minus the slashes - at debuggex and it will visually show you the "One of" condition of what you've posted here. Then compare that to these two others on the site: ^depth\d+$ and ^depth(\d+)$ Leave out the ^ and $ anchors to see how those differ. Commented Jun 9, 2015 at 19:40

2 Answers 2

2

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"
Sign up to request clarification or add additional context in comments.

1 Comment

How can I always return the first one, if there are multiple "depth*" substrings? may be matches[0] ?
1

$ 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])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.