JS问题:我怎样才能使它,当我检测到一个字符串中的单词,我检查独立的单词,如Hello



如何检查"Hello"在if语句的字符串内,但它应该只检测单词"Hello"孤独而不像"你好";或";HHello"

最简单的方法是使用正则表达式。通过使用正则表达式,您可以定义一个规则来验证特定的模式。下面是你需要匹配的模式的规则:

  • 单词必须包含字符串"hello">
  • 字符串"hello"必须在空格之前,否则必须是要匹配的字符串的开头。
  • 字符串"hello"必须后跟一个'。'或空白,否则必须在要匹配的字符串的末尾找到。

下面是实现上述规则的简单js代码:

let string = 'Hello, I am hello. Say me hello.';
const pattern = /(^|s)hello(s|.|$)/gi;
/*const pattern = /bhellob/ you can use this pattern, its easier*/
let matchResult = string.match(pattern);
console.log(matchResult);

在上面的代码中,我假设模式不区分大小写。这就是为什么我在模式之后添加了不区分大小写的修饰符(" I ")。我还添加了全局修饰符("g")来匹配字符串"hello"的所有出现。

您可以将规则更改为您想要的任何内容,并更新正则表达式以确认新规则。例如,您可以允许字符串后面跟着"!"。您可以通过简单地添加"| "后,"美元。

如果你不熟悉正则表达式,我建议你访问W3Schools参考:https://www.w3schools.com/jsref/jsref_obj_regexp.asp

实现这一目标的一种方法是首先替换字符串中的所有非字母字符,例如hello, how are you@NatiG的答案此时将失败,因为单词hello与前导,一起存在,但没有空格。一旦所有的特殊字符被删除,你可以简单地将字符串拆分为单词数组,并从那里过滤'hello'。

let text = "hello how are you doing today? Helloo HHello";
// Remove all non alphabetical charachters
text =  text.replace(/[^a-zA-Z0-9 ]/g, '')
// Break the text string to words
const myArray = text.split(" ");
const found = myArray.filter((word) => word.toLowerCase() == 'hello')
// to check the array of found ```hellos```
console.log(found)
//Get the found status
if(found.length > 0) {
console.log('Found') 
}

结果

['hello']
Found

最新更新