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?
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With