23

I have a string delimited like so (it's not an array it's a straight string)

string = " [United States] [Canada] [India] ";

I want to do something like below.

if( string contains "Canada" ) {
 //Do Canada stuff here
}

Thanks for any tips

cнŝdk
  • 31,391
  • 7
  • 56
  • 78
Talon
  • 4,937
  • 10
  • 43
  • 57

2 Answers2

7
var string = '[United States][Canada][India]';
var search = 'Canada';
if (string.indexOf('[' + search + ']') !== -1) {
  // Whatever
}
Sam Blake
  • 657
  • 6
  • 13
qw3n
  • 6,236
  • 6
  • 33
  • 62
  • This is the right way to do it, except that you should be checking that `indexOf` isn't returning `-1`, otherwise your check would fail for the first item in the list as it would return `0`. – Matthew Apr 04 '12 at 16:54
  • @Matt Thanks your absolutely correct. I actually meant to put `>-1` and got distracted and didn't even realize my mistake. – qw3n Apr 05 '12 at 02:56
3

Just extend the String methods... as a bonus i added a case-insensitive match

// Only line you really need 
String.prototype.has = function(text) { return this.toLowerCase().indexOf("[" + text.toLowerCase() + "]") != -1; };

// As per your example
var Countries = " [United States] [Canada] [India] ";

// Check Spain
 if (Countries.has("Spain")) {
   alert("We got Paella!");
} 
// Check Canada
if (Countries.has("Canada")) {
   alert("We got canadian girls!");
}
// Check Malformed Canada
 if (Countries.has("cAnAdA")) {
   alert("We got insensitive cAnAdiAn girls!");
}
// This Check should be false, as it only matches part of a country
if (Countries.has("Ana")) {
   alert("We got Ana, bad, bad!");
} 

Demo: http://jsfiddle.net/xNGQU/2/