Find if value is contained in comma separated values in JS
This would work:
if( first.match(new RegExp("(?:^|,)"+second+"(?:,|$)"))) {
// it's there
}
First, split your String to an array:
var second = 'cat';
var first = 'dog,cat,lion';
var aFirst = first.split(',');
Then cycle through your new array
for (var i = 0; i < aFirst.length; i++) {
if (aFirst[i] == second) {
alert('jay!');
}
}
You can use Array.indexOf
:
if( first.split(',').indexOf(second) > -1 ) {
// found
}
Need IE8- support? Use a shim: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/indexOf