Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
67
rated 0 times [  69] [ 2]  / answers: 1 / hits: 31328  / 10 Years ago, fri, august 8, 2014, 12:00:00

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.


More From » jquery

 Answers
32

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.


[#69852] Wednesday, August 6, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
dylondarrianb

Total Points: 48
Total Questions: 109
Total Answers: 104

Location: Zambia
Member since Thu, Jun 25, 2020
4 Years ago
;