使用String.prototype.contains()
方法,你可以搜索字符串中的子字符串。例如,
"Hi there everyone!".contains("Hi"); //true
"Hi there everyone!".contains("there e"); //true
"Hi there everyone!".contains("goodbye"); //false
您還可以使用Array.prototype.indexOf()
到類似的效果:
("Hi there everyone!".indexOf("Hi") > -1) //true
("Hi there everyone!".indexOf("Hmmn") > -1) //false
然而,在這種方法中,我們甚至不需要使用任何上述方法,爲.match()
方法將爲我們完成所有操作:
要返回匹配關鍵字的數組,請使用.match()
。它接受一個正則表達式作爲參數,並返回一個匹配正則表達式的子串的數組。
var checkTitle = "5 monkeys jumping on the bed";
var compareTitle = "5 , monkeys";
/* ^^^
It is very important to separate each word with space-comma-space */
function getWords(str){ //returns an array containing key words
return str.split(" , ");
}
function matches(str, words){
var patt = "";
for (var i = 0; i < words.length; i++){
patt = (i > 0)? patt + "|" + "(" + words[i] + ")" : patt + "(" + words[i] + ")";
}
patt[patt.length-1] = "";
patt = new RegExp(patt, 'gi');
// ^i makes it case-insensitive
return str.match(patt);
}
matches(compareTitle, getWords(checkTitle)); // should return ['5','monkeys']
您可以檢查是否通過這樣做存在匹配:
if (matches(compareTitle, getWords(checkTitle))){
// matches found
}
如果這個答案是比第一更好,接受這一而是一個。尋求更多的幫助,或者它不起作用。
正則表達式? – 2014-11-14 17:28:36