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?
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!
There are some differences between the code you have in Perl and JS:
$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 textm[1] - the contents of Group 1 (capture group 1)m.index - the 0-based index of the match in the stringm.input - the original stringIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With