0

in another article on Stackoverflow, I found this line of code

myString = 'hello112';
myNumber = myString.match(/\d+/)[0];

In this case, the 'myNumber' variable has the value of 122.

But when I use .match for the following case, it fails:

myColor = 'rgb(210,255,105);
myNumbers = myColor.match(/\d+/);

The 'myNumbers'variable is an array, but it's length is 1 and it contains only '210' and not the other 2 numbers.

Is there a way in Javascript that I can achive something like this?

input = 'rgb(210,255,105);
output = [210,255,105];

Thank you very much.

1
  • use the global modifier g: /\d+/g Commented Feb 11, 2017 at 13:51

2 Answers 2

3

Unless told otherwise, match() matches only the first instance, not all. You need the global "g" flag after the pattern.

match(/pattern/g);

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp

Side note: you can't use the global modifier in conjunction with sub-group matching, but that shouldn't affect your situation.

Sign up to request clarification or add additional context in comments.

Comments

1

You have to use g - global flag.

myColor = 'rgb(210,255,105)';
console.log(myColor.match(/\d+/g));

2 Comments

Thank you very much! It worked! Have a nice day bro :)
@LanMai My pleasure, have a great day too.

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.