Reputation: 2724
I have a string of IDs in CSV format in an input box
12,23,26,32
I have to check if this string contains 23 or 24, if yes then return false, else return true
Upvotes: 0
Views: 274
Reputation: 13631
!/(^|,)2[34](,|$)/.test( str );
or if there may be whitespace present
!/(^|,)\s*2[34]\s*(,|$)/.test( str );
The RegExp test
method returns true
if the string argument matches the regular expression or false
if it doesn't. The !
inverts the result of the test call.
^
is the metacharacter for the start of the string, so(^|,)
means either 'at the start of the string' or 'one comma character'.
It can't be written [^,]
as that would mean 'one character that isn't a comma', and it can't be written [,^]
as that means 'one character that is either a comma or a literal ^
character.
2[34]
means 2 followed by 3 or 4.
(,|$)
means a comma or the end $
of the string.
\s*
means zero or more space characters.
Upvotes: 1
Reputation: 5818
var str = "12,23,26,32";
var obj = str.split(",");
var isFound = false;
for(i=0; i < obj.length; i++)
{
if(obj[i] == "23" || obj[i] == "24")
{
isFound = true;
break;
}
}
return isFound;
Upvotes: -1
Reputation: 1129
Use indexOf. You can check if it contains a subString. If not found, it returns -1
var str = "12,23,26,32"
return !(str.indexOf("23")!=-1 || str.indexOf("24")!=-1) // Dont have 23 or 24
=======EDIT=======
Like @Matt said in comment, this solution will work also to "12,239,26,32" and thats not the point.
Make the split before check the indexOf, then you will get the element between the commas.
var array = "12,23,26,32".split(",");
return !(array.indexOf("23")!=-1 || array.indexOf("24")!=-1) // Dont have 23 or 24
Upvotes: 1
Reputation: 1590
Try this
var str = "12,23,26,32";
var isFound = (str.indexOf('23') || str.indexOf('24')) > -1;
Upvotes: 0
Reputation: 123387
if (/(?:^|,)(23|24)(?:,|$)/.test("12,23,26,32")) {
/* found 23 or 24 */
}
Upvotes: 0