Hommer Smith
Hommer Smith

Reputation: 27852

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?

Upvotes: 10

Views: 28515

Answers (5)

cbayram
cbayram

Reputation: 2259

var first = 'dog, cat, lion';
var second = 'cat';
// \b is a word boundary
// a word character, \w, consists of letters, digits and underscore
// remove the second paramater "i" if you want case-sensitive match
var containsRE = new RegExp(second, "i"); 
var startsWithRE = new RegExp("\\b"+second, "i"); 
var endsWithRE = new RegExp(second+"\\b", "i"); 
var exactRE = new RegExp("\\b"+second+"\\b", "i"); 
// test exactRE, for example, like so
if(exactRE.test(first)) {
    // matched
}

Upvotes: 0

David Hellsing
David Hellsing

Reputation: 108500

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

Upvotes: 29

Usha
Usha

Reputation: 1468

var first = 'dog,cat,lion';
var stringArray = first.split(',');       
for (var i=0; i<stringArray.length; i++) {
    if (stringArray[i].match("cat")) {
          alert('Its matched');
      }
 }

Upvotes: 1

Zim84
Zim84

Reputation: 3497

First, split your String to an array:

var second = 'cat';
var first = 'dog,cat,lion';
var aFirst = first.split(',');

Then cycle through your new array

for (var i = 0; i < aFirst.length; i++) {
    if (aFirst[i] == second) {
        alert('jay!');
    }
}

Upvotes: 1

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324650

This would work:

if( first.match(new RegExp("(?:^|,)"+second+"(?:,|$)"))) {
    // it's there
}

Upvotes: 11

Related Questions