Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does JavaScript regex matching require repeated code?

Consider the following regex code snippet in Perl:

if ($message =~ /^(.+) enters the race!$/)) {
    $racer = $1;
    print "Found $racer";
} else {
    print "Racer parsing error!";
}

I'm trying to port this to JavaScript, and here's what I have come up with:

if (message.match(/^.+ enters the race!$/)) {
    var racer = message.match(/^(.+) enters the race!$/)[1];
    console.log("Found " + racer);
} else {
    console.log("Racer parsing error!");
}

Notice how the regex has to be repeated twice. This look sloppy. Not to mention that it wastes processing power since it has to do the same regex twice in a row. Is there any way to make this code snippet look cleaner?

like image 578
James Avatar asked Nov 23 '25 21:11

James


2 Answers

You can check the regex match right in the if statement. Something like this would work:

JavaScript

function check(message) {
    if (racer = message.match(/^(.+) enters the race!$/)) {
    console.log("Found " + racer[1]);
    } else {
    console.log("Racer parsing error!");
    }
}


check("blah enters the race!")
check("blah blah blah")

Output

Found blah
Racer parsing error!

like image 142
Adam Konieska Avatar answered Nov 26 '25 10:11

Adam Konieska


There are some differences between the code you have in Perl and JS:

  • JS does not have string interpolation, so your code has to be a bit verbose
  • There are no $1-like global variables, though you can declare it and use in code.

You can first match and check if the regex matched anything.

var message = "John enters the race!";
var m = message.match(/^(.+) enters the race!$/); // Match the string with a pattern
if (m) {                                          // Check if there is a match
    var racer = m[1];                             // Assign the captured substring to `racer`
    console.log("Found " + racer);              
} else {
    console.log("Racer parsing error!");
}

Note that m here is a Match object containing:

  • m[0] - the whole matched text
  • m[1] - the contents of Group 1 (capture group 1)
  • m.index - the 0-based index of the match in the string
  • m.input - the original string
like image 26
Wiktor Stribiżew Avatar answered Nov 26 '25 10:11

Wiktor Stribiżew



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!