简体   繁体   English

字符串包括:测试字符串数组中的单词

[英]String Includes: test the word from an array of strings

 var sentence = 'The quick brown fox jumped over the lazy dog.'; var word = ['fox']; console.log('The word "' + word + (sentence.includes(word)? '" is' : '" is not') + ' in the sentence'); // expected output: "The word "fox" is in the sentence" 

This is the String.includes() in the Javascript docs but what I want to do is something like this: 这是Javascript文档中的String.includes() ,但我想要做的是这样的:

 var sentence = 'The quick brown fox jumped over the lazy dog.'; var word = ['fox', 'dog']; console.log('The word "' + word + (sentence.includes(word)? '" is' : '" is not') + ' in the sentence'); 

I want to test an array of strings to the sentence and return true if one of the strings in the array are in the sentence. 我想测试一个字符串数组到句子,如果数组中的一个字符串在句子中,则返回true But as you can see in the snippet, it does not work. 但正如您在片段中看到的那样,它不起作用。

I assume it prints for each item in variable word So like 我假设它为变量word每个项目打印

 "The word "fox" is in the sentence"
 "The word "dog" is not in the sentence"

You can do 你可以做

 var sentence = 'The quick brown fox jumped over the lazy dog.'; var word = ["fox", "dog"] function test(word) { console.log('The word "' + word + (sentence.includes(word) ? '" is' : '" is not') + ' in the sentence'); } word.map((item) => { return test(item) }) 

try this one instead, if one of the var word does not match at the sentence, it'll return false else if everything is included then it will return true. 试试这个,如果其中一个var word在句子中不匹配,它将返回false,否则如果包含所有内容则返回true。

 var sentence = 'The quick brown fox jumped over the lazy dog.' var word = ["fox", "the", "lol"] var initialReturn = true check = (word) => { !sentence.includes(word) ? initialReturn = false : null } word.map(item => { return check(item) }) console.log("initialReturn", initialReturn) 

 var sentence = 'The quick brown fox jumped over the lazy dog.'; var word = ['fox', 'dog']; console.log('The word "' + word + (sentence.split(' ').some(d => word.includes(d)) ? '" is' : '" is not') + ' in the sentence'); 

Check this piece of code. 检查这段代码。 I learned one important thing working with strings. 我学会了一个使用字符串的重要事情。 Regular expressions can help you (but it's hell) and use extensions (functions, helpers) in your framework is you're using it. 正则表达式可以帮助你(但它是地狱)并在你的框架中使用扩展(函数,帮助器)你正在使用它。 But if you use native js indexOf will help you. 但是如果你使用原生js indexOf会帮助你。 I updated my answer a bit. 我稍微更新了我的答案。

 var sentence = 'The quick brown fox jumped over the lazy dog.'; var words = ['fox', 'dog']; console.log('The words: "' + words + (sentence.split(/[ ,.]/).some(function(e) { return words.indexOf(e) >= 0 })? '" is' : '" is not') + ' in the sentence'); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM