dsaket
dsaket

Reputation: 1896

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.

Upvotes: 5

Views: 28806

Answers (4)

Muhammad Ridwan
Muhammad Ridwan

Reputation: 9

var str = "10M255S"
var result = str.match(/([0-9])/g)

var value = []
result.map(res => {
  value += res
})
console.log(value)

Upvotes: 0

RamblinRose
RamblinRose

Reputation: 4963

K-Gun's answer makes sense if the pattern never varies, however if 'M' and 'S' are simply placeholder examples for arbitrary text, then use the RegExp /\d+/g

<!DOCTYPE html>
<html>
<head>
  <script>
    function fn() {
      var re = /\d+/g, // match digits, globally
        str = '10M225S',
        result = [],
        temp;
      // process successive matches
      while ((temp = re.exec(str)) !== null)
        result.push(temp[0]);

      document.getElementById("result").innerText = result.toString();
    }
  </script>
</head>
<body onload="fn()">
  <h1 id="result"></h1>
</body>
</html>

Here's a plunkr demonstrating the code.

The RegExp re will match runs of digits. This will work regardless of any non-digit characters, e.g. it would match "10ZXZZ225FOZ".

Upvotes: 0

Terminater
Terminater

Reputation: 316

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.

Upvotes: 15

iHasCodeForU
iHasCodeForU

Reputation: 177

you can use .split() to split the strings:

var str = "10M225S"
var m = str.split("M")[0];
var s = str.split("M")[1].split("S")[0];

console.log("m >>> " + m);
console.log("s >>> " + s);

no need for regular expressions in this case.

Upvotes: 2

Related Questions