1

I understand how to use the regular expressions in JS and PHP. I'm trying to switch some of my PHP code to JS and I have a function that goes through different regular expressions to see if it can find a match.

Example PHP:

if(preg_match('/regex1/', $string, $matches)) { 
    $output = $matches[1]; 
} else if(preg_match('/regex2/', $string, $matches)) {
    $output = $matches[1];
} else etc....

Is there a way to do something similar in JS?

The only way I can think of doing it is:

if(string.match(/regex/)) {
   var res = string.match(/regex/);
   output = res[1];
} else if ..... and so on

I'd rather not have it do the match twice... Is there another way?

Thanks for your help.

3 Answers 3

1

You could do:

var res;
if(res = string.match(/regex/)) {
   output = res[0];
} else if ..... and so on

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

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

2 Comments

This is great. Just test it with: if(res = string.match(/regex/)) and seems to work fine. Any reason to keep the "!== null" since the condition already checks that?
@tathyler, no, since even an empty array or array with a single falsey element is going to return a truthy value.
0

You could build an array of regexs like this:

var array = ["/regex1/", "/regex2/", "/regex3/", "/regex4/"];
var x;
for (index = 0; index < array.length; ++index) {
    if(string.match(array[index]))){
        x++;
        output = matches[x]; 
    }
}

1 Comment

He's wanting javascript.
0

Take a look at MDN's docs on Regular expressions, specifically the available methods. I think what you want here is the exec method rather than match, as that will return an array of matched results, just like preg_match in PHP. You will likely need to store the result of the exec call first, and then in your conditions you should check for a length on the result.

var matches = mystring.exec(/regex1/);
var output;

if (matches.length) {
  output = matches[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.