Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Regular Expressions to Extract Values in Javascript

I have a string in the form: "xMyS"

I want to extract x and y in using the Javascript Regex expressions.

For example, if the string is

10M225S

I need 10 and 225 from this.

Also, the string might not have either of x or y part. For example it can be just 225S or just 10M.

EDIT: I tried things like .match(), but don't know how to extract values in the mentioned format.

EDIT: The regex I tried so far is /(\w+)M(\w+)S/, but it seems to only work for 10M225S and not for 10M and 225S.

like image 594
dsaket Avatar asked Aug 28 '26 20:08

dsaket


1 Answers

You can do something like this:

var str = "10M255S"
var match = str.match(/^([0-9]*)M*([0-9]*)S*$/)

Then match[1] is 10 and match[2] is 255

If var str = "10M", then match[1] is 10 and if var str = "255S", then match[1] is 255

In any of the three cases, matches start from second element of the array match.

Hope this helps.

like image 111
Terminater Avatar answered Aug 30 '26 10:08

Terminater



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!