0

One of our legacy JavaScript code contains this line of code:

code.match(/if\\s*\\(/g).length

What does this /if\\s*\\(/g regex mean?

1
  • 1
    this will show you an error. Commented Feb 16, 2015 at 6:03

2 Answers 2

1

It means match "if" followed by whitespace "zero or more" times and an open parentheses. Except it should error because of the double escapes, the regular expression would be:

code.match(/if\s*\(/g).length

A regular expression literal does not use double escapes, they're used in RegExp Objects.

var re = new RegExp('if\\s*\\(', 'g')
code.match(re).length;

In other words:

Regular expression visualization

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

2 Comments

It all makes sense now. Not sure why it has double escapes. Thank you.
Double escapes can be valid. It just changes the meaning to: i followed by f followed by \ followed by zero or more s then \(
0

The match() method searches a string for a match against a regular expression, and returns the matches, as an Array object.

Search a string for "ain":

  var str = "The rain in SPAIN stays mainly in the plain"; 
  var res = str.match(/ain/g);

The result of res will be an array with the values:

  ain,ain,ain

See more: http://www.w3schools.com/jsref/jsref_match.asp

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.