23

我有一个这样分隔的字符串(它不是一个数组,它是一个直字符串)

string = " [美国] [加拿大] [印度] ";

我想做下面的事情。

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

感谢您的任何提示

4

2 回答 2

7
var string = '[United States][Canada][India]';
var search = 'Canada';
if (string.indexOf('[' + search + ']') !== -1) {
  // Whatever
}
于 2012-04-04T15:42:45.260 回答
3

只需扩展 String 方法...作为奖励,我添加了不区分大小写的匹配

// 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!");
} 

演示:http: //jsfiddle.net/xNGQU/2/

于 2012-04-04T16:01:14.283 回答