4

I have to match some strings from the given variables. Say I have variable

var x = 'elseif testing';

Now I want get value "testing" from this string. So wrote.

x.match(/^elseif(.*)/);

Late I realized sometimes I do get string:

var x = 'else if testing';

So I wrote expression to match:

x.match(/^else[\s+]if(.*)/);

This works well on browser but not in Node.js. Any reason why ?

2
  • 1
    Note that this doesn't "work well in browers" - try it, it behaves the same in browsers as in node.js - that is, it matches else if and else \t if but not elseif. The + modifier means 1 or more. You want the * modifier which means 0 or more. Commented Dec 11, 2013 at 19:18
  • 1
    so, there is no difference between browser and node.js? Commented Dec 11, 2013 at 19:51

2 Answers 2

2

Try without double escapes and character class:

x.match(/^else\s*if(.*)/i);

Also added i for case insensitive search.

Also note [\s+] will also match a literal + since inside character class + (and many other regex special characters) is considered a literal plus.

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

Comments

0

If you're explicitly wanting to match only one or zero spaces, then:

x.match(/^else\s?if(.*)/i);

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.