1
> "1fff=*; style=mobile".match("[\s]*")
[ '', index: 0, input: '1fff=*; style=mobile' ]
> "1fff=*; style=mobile".match("[^;]*")
[ '1fff=*', index: 0, input: '1fff=*; style=mobile' ]
> "1fff=*; style=mobile".match('(^|;)[\s]*style=([^;]*)')
null
> "1fff=*; style=mobile".match(/(^|;)[\s]*style=([^;]*)/)
[ '; style=mobile',
  ';',
  'mobile',
  index: 6,
  input: '1fff=*; style=mobile' ]

str.match(str) can work partially as regex mode, but there is some difference.

What exactly is the difference?

3
  • 1
    see doc about String.match : If the regular expression does not include the g flag, returns the same result as RegExp.exec(). The returned Array has an extra input property, which contains the original string that was parsed. In addition, it has an index property, which represents the zero-based index of the match in the string. Commented Apr 29, 2015 at 15:54
  • I just want know why the third one is null? Commented Apr 29, 2015 at 16:19
  • you don't have the g flag, so the same result as RegExp.exec(). If the match fails, the exec() method returns null. Commented Apr 29, 2015 at 16:23

1 Answer 1

1

The difference is that in a string literal, \s just means s — there's no \s escape-sequence for string literals, so the \ gets dropped.

If you want to use a string literal, and you need the regex to contain \s, then the string literal needs to contain \\s (with an extra backslash) so the string will contain \s:

> "1fff=*; style=mobile".match('(^|;)[\\s]*style=([^;]*)')
; style=mobile,;,mobile

(I recommend sticking with a regex literal, though.)

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

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.