关于javascript:异常分隔字符串时检测字符串是否包含其他字符串

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

本问题已经有最佳答案,请猛点这里访问。

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

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

我想做下面这样的事情。

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

谢谢你给我小费


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


extend the只是字符串的方法。所有奖金added as a钝感的家园比赛P></

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// 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:/ / / / / 2 xngqu jsfiddle.netP></