如何在字符串中找到一组特定的单词(在本例中为gval)定义为特定的单词集?
if(gval.indexOf("define") > -1){
console.log("Yo! gval contains Define");
}
var gval = input.val().trim().toLowerCase();
答案 0 :(得分:1)
如果您想找到" wordset" ,那么您需要使用预期字的Array
需要然后利用 jQuery 库提供的$.inArray功能,您可以尝试以下方法:
现场演示: http://jsfiddle.net/t52aLmcz/
var text = 'this is a text that contains defined word',
textWords = text.split(' '), // create array of text words
expectedWords = ['defined', 'this'], // expected words to be found
word;
for (var i in textWords) {
word = textWords[i];
if($.inArray(word, expectedWords) != -1) {
break; // if one of the expected words is found, do a break
}
}
if (word) { // word exists
console.log('Your text contains: ' + word);
}
答案 1 :(得分:1)
也许你可以使用.split()来解决你的问题。 创建一个包含每个单词的数组。循环查看该单词是否等于n#39; gval'。
示例强>
<head>
</head>
<body>
<h1 id=gval>In this sentence is a word gval and i want to find it! maybe more then once? gval gval</h1>
<h2 id=outcome></h2>
<script>
var string = document.getElementById('gval').innerHTML; //create the string you want to check.
var stringArray = string.split(' ');// Split the string every time it sees an space ' '.
var ammount = 0;//This wil be the ammount of 'gval' there are in the sentence.
for(i = 0; i < stringArray.length;i++){ // Loop through the length of the array.
if(stringArray[i] == 'gval'){ // Check if the word is the same as 'gval'.
ammount++;//If the word is the same as 'gval' increment ammount with +1.
}
}
document.getElementById('outcome').innerHTML = ammount;//set the text in the H2 with id outcome to the ammount.
</script>
</body>
答案 2 :(得分:0)
如果您正在寻找不区分大小写的搜索,请使用此方法。你首先需要设置变量gval,然后才能检查indexOf
var gval = input.val().trim().toLowerCase();
if(gval.indexOf("define") > -1){
console.log("Yo! gval contains Define");
}