views:

42

answers:

2

If I do this:

var string = "7,11,2"
var check = string.match("/1/");

if(check != null){
    doSomething();
} else {
    doSomethingElse();
}

Then check is not null because match has found 1 in 11. So how should I avoid this and get 1 when it really appears?

+3  A: 

That is happening because it matches a 1 in 11 and calls it a match. You have to make sure that there isn't another number following the 1. Try:

var check = string.match("/(^|\D)1(\D|$)/");

This will look for a way surrounded by characters that are not digits, or the start/end of string (the ^ and $ anchors).

NullUserException
Thanks very much it works perfectly!! I will accept your answer as soon as I can!
CIRK
@zolex Please show what input would break the regex
NullUserException
this regex only works for this special case. see my upcomming answer for a regex to check if a value is in a somehow separeted list...
zolex
ah sure sorry, misread. just additionally gonna solve it with lookaround :D
zolex
@zolex Word of warning: JS doesn't support lookbehind.
NullUserException
oh, too bad, thanks for the info
zolex
One suggestion (not relevant in this case, but in general): By using `/(^|\D)1(?=\D|$)/` instead, you'd allow this regex to match both `1` s in `1,1`. This would fail now because the comma is used up in the first match.
Tim Pietzcker
+1  A: 

Another way would be to surround it with word boundary anchors: /\b1\b/ will only match a 1 if it is not surrounded by other numbers, letters, or underscore. So it would work in your case (and is a bit more readable).

It will, however, fail in cases like ID1OT - if you wanted to extract the 1 from there, you could only do that with @NullUserException's method.

Tim Pietzcker
What kind of id1ot would use that though?
NullUserException