Detect if a String Contains Another String when the string is delimited unusually [duplicate]

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

var string = '[United States][Canada][India]';
var search="Canada";
if (string.indexOf('[' + search + ']') !== -1) {
  // Whatever
}

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/


The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .
Read More:   How to handle file downloads with JWT based authentication?

Similar Posts