Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find if value is contained in comma separated values in JS

Given these two strings:

var first = 'dog,cat,lion';
var second = 'cat';

How would I do it to know if the second var is any of the words (the ones that are separated by commas) in the first vars?

like image 440
Hommer Smith Avatar asked Nov 09 '12 18:11

Hommer Smith


People also ask

How do I check if a string contains a comma?

We have a global variable myString which holds a string as its value. In the event handler function, we are using the includes() method and ternary operator ( ? ) to verify whether myString contains a comma or not. Depending upon the result of the check, we will assign “Yes” or “No” to the result variable.

What is Comma Separated Values in JavaScript?

A comma-separated valuation (CSV) file is a demarcated file format that uses a comma to isolate the values. The data record is comprised of one or more than one field, separated by the commas. The name root for this file format is the comma-separated file format, is the use of the comma as a field extractor.


2 Answers

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

like image 55
David Hellsing Avatar answered Oct 04 '22 18:10

David Hellsing


This would work:

if( first.match(new RegExp("(?:^|,)"+second+"(?:,|$)"))) {
    // it's there
}
like image 34
Niet the Dark Absol Avatar answered Oct 04 '22 20:10

Niet the Dark Absol