Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Separate by comma (,) and check if any of the values is = "something"

How can I somehow split/separate my JavaScript variable by comma (,).
And then check if value-of-any-of-the-separated-strings = "something"

For example, my variable has the value 1,2,3,4,5,6,7,8,9,10,2212312, and I want to check if any of the numbers are = 7 in a IF-Statement.

Does anyone have any ideas how this can be done?

like image 504
Mark Topper Avatar asked Oct 05 '12 14:10

Mark Topper


2 Answers

First, split the string by ",". Then, use indexOf on the split-string array to see if the target string is found (-1 means it wasn't found in the array). For example:

var str = "1,2,3,4,5,6,7,8,9,10,10,2212312";
var split_str = str.split(",");
if (split_str.indexOf("7") !== -1) {
    // Original string contains 7
}

References:

  • String.prototype.split - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split
  • Array.prototype.indexOf - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf
like image 156
Ian Avatar answered Nov 14 '22 22:11

Ian


This is a simple application of Array.prototype.some:

var yourVar = '1,2,3,4,5,6,7,8,9,10,2212312';
function isSeven(val) {
    return val === '7';
}
if (yourVar.split(',').some(isSeven)) {
    //do stuff
}

Another common way this could be written is:

if (~yourVar.split(',').indexOf('7')) {
    //do stuff
}

Or if Array.prototype.contains has been defined:

if (yourVar.split(',').contains('7')) {
    //do stuff
}

Or if you want to use a regular expression:

if (/(?:^|,)7(?:,|$)/.test(yourVar)) {
    //do stuff
}

Note: Array.prototype.some, Array.prototype.indexOf and Array.prototype.contains all require polyfills to work correctly cross browser.

like image 39
zzzzBov Avatar answered Nov 15 '22 00:11

zzzzBov