Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript REGEX: How to get `1` and not `11`

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?

like image 273
Adam Halasz Avatar asked Sep 25 '10 03:09

Adam Halasz


2 Answers

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).

like image 138
NullUserException Avatar answered Oct 11 '22 09:10

NullUserException


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.

like image 43
Tim Pietzcker Avatar answered Oct 11 '22 07:10

Tim Pietzcker