当字符串异常分隔时,检测字符串是否包含另一个字符串

时间:2012-04-04 15:39:51

标签: javascript jquery string

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

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

我想做类似下面的事情。

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

感谢您提供任何提示

2 个答案:

答案 0 :(得分:7)

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

答案 1 :(得分: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/