I have string like this: str = "ball, apple, mouse, kindle";
and I have another text to search in this string: search = 'apple';
How to determine using JavaScript if apple
exist in comma delimited string?
P.S: str
can be with or without spaces between comma and next item.
Simple solution:
var str = "ball, apple, mouse, kindle";
var hasApple = str.indexOf('apple') != -1;
However, that will also match if str
contains "apple fritters":
var str = "ball, apple fritters, mouse, kindle";
var hasApple = str.indexOf('apple') != -1; // true
There are different approaches you could do to get more specific. One would be to split the string on commas and then iterate through all of the parts:
var splitString = str.split(',');
var appleFound;
for (var i = 0; i < splitString.length; i++) {
var stringPart = splitString[i];
if (stringPart != 'apple') continue;
appleFound = true;
break;
}
NOTE: You could simplify that code by using the built-in "some" method, but that's only available in newer browsers. You could also use the Underscore library which provides its own "some" method that will work in any browser.
Alternatively you could use a regular expression to match "apple" specifically:
var appleFound = /\Wapple,/.test(',' + str + ',');
However, I think your real best bet is to not try and solve this yourself. Whenever you have a problem like this that is very common your best bet is to leverage an existing library. One example would be the Underscore String library, especially if you're already using Underscore. If not, there are other general purpose string utility (eg. String.js) libraries out there you can use instead.
To really test whether the exact character sequence "apple" is an item in your comma separated list (and not just a substring of the whole string), you can do (considering optional spaces before and after the value):
If Array#indexOf
is available:
var items = str.split(/\s*,\s*/);
var isContained = items.indexOf('apple') > -1;
If Array#some
is available:
var items = str.split(/\s*,\s*/);
var isContained = items.some(function(v) { return v === 'apple'; });
With a regular expression:
var isContained = /(^|,)\s*apple\s*($|,)/.test(str);
you can turn the string in to an array and check the search string is in it.
var stuffArray = str.split(",");
var SearchIndex = stuffArray.indexOf("Apple");
the search SearchIndex represent the position in the array. if the SearchIndex < 0 the item is not found.
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