如何拆分字符串然后将其与另一个字符串匹配

时间:2012-08-15 12:03:24

标签: javascript split

让我坐下来我有句子“我喜欢饼干”和句子“I_like_chocolate_cookies”。 如何拆分字符串“我喜欢cookie”并检查第二句中是否存在单词?

4 个答案:

答案 0 :(得分:1)

喜欢这个

var words = "I like cookies".replace(/\W/g, '|');
var sentence = "I_like_chocolate_cookies";

console.log(new RegExp(words).test(sentence));

https://tinker.io/447b7/1

答案 1 :(得分:0)

以下是一些示例代码:

str1 = 'I like cookies'
str2 = 'I_like_chocolate_cookies'
// We convert the strings to lowercase to do a case-insensitive check. If we
// should be case sensitive, remove the toLowerCase().
str1Split = str1.toLowerCase().split(' ')
str2Lower = str2.toLowerCase()
for (var i = 0; i < str1Split.length; i++) {
  if (str2Lower.indexOf(str1Split[i]) > -1) {
    // word exists in second sentence
  }
  else {
    // word doesn't exist
  }
}

希望这有帮助!

答案 2 :(得分:0)

像这样?

var x ="i like grape";
var c ="i_don't_like";
var xaar = x.split(' ');
for(i=0;i<xaar.length;i++){
if(c.indexOf(xaar[i])>-1) console.log(xaar[i]);

}

答案 3 :(得分:0)

var foo = "I_like_chocolate_cookies";
var bar = "I like chocolate cookies";

foo.split('_').filter(function(elements) {
  var duplicates = []
  if(bar.split().indexOf(element) != -1) {
    return true;
  }
});