【问题标题】:Find a specific word in a string在字符串中查找特定单词
【发布时间】:2019-02-20 11:47:03
【问题描述】:

我想检查一个字符串是否确实包含一个特定的单词。像这样,

问题

  • "word"字符串包含,"word"字,同;

  • "daword"字符串包含,"word"字,同;

  • "dawordo" 字符串包含,"word" 字。

我想要什么?

  • "word" 字符串应该确实包含,"word" 字,与;

  • "(whitespaces)word(whitespaces)" 字符串应该确实包含,"word" 字,与;

  • "da word" 字符串应该真的包含,"word" 字一样;

  • "da word o" 字符串应该确实包含,"word" 字一样;

  • "(white spaces)word" 字符串应该真的包含,"word" 字一样;

  • "word(white spaces)" 字符串应该真的包含,"word" 字一样;


如何在 JavaScript 中做到这一点?谢谢!

【问题讨论】:

  • 所以.. \bword\b?
  • 我很困惑。我什么都不懂。
  • @George 你该死的对!我不知道正则表达式中的\b 特殊字符,感谢您提供这些重要信息。谢谢,成功了!
  • @MuhammedÇağlarTUFAN 不客气。

标签: javascript regex string match


【解决方案1】:

正则表达式\bword\b 可以解决问题。

// should use \b with regex
var str = 'testwordtest';
if(str.match(/\bword\b/)){
    console.log('match');
} else {
    console.log('no match');
}

【讨论】:

  • @MuhammedÇağlarTUFAN 没关系,我误解了编辑。
【解决方案2】:

使用String.includes

const target = 'word';
const arr = ['word', ' word ', 'hello_word', 'not_here'];

arr.forEach(w => console.log(w, w.includes(target)));

【讨论】:

  • 感谢回复,但问题是这样的:)我找到了解决方案。使用正则表达式,\bword\b 很好!
  • 我确实在答案中准确解释了问题,在字符串'hello_word''word' 不应该匹配,像这样'hello word' 应该匹配。
  • 你没有。假设dawordo 返回true,那为什么hello_word 不会呢?你的问题不够详细
  • 在我的问题中,为什么dawordohello_word 应该返回true,如您所见?
  • 您确实要求这样做 "dawordo" string contains, "word" word
【解决方案3】:

您可以使用 indexof 函数。如果句子不包含您要查找的单词,这将返回 -1,否则将返回偏移量。

https://www.w3schools.com/jsref/jsref_indexof.asp

如果您不区分大小写,我建议稍微修改示例以首先将字符串转换为小写。

var str = "Hello world, Welcome to the universe.";
var n = str.toLowerCase().indexOf("welcome");
if(n > -1)
{
    console.log("The search string was located at offset " + n);
}
else
{
    console.log("The string did not contain the search string...");
}

【讨论】:

  • 感谢回复,但问题是这样的:)我找到了解决方案。使用正则表达式,\bword\b 很好!
  • @PaulIshak 因为正如 OP 所说,这并不能解决问题
猜你喜欢
  • 2019-05-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-13
  • 1970-01-01
  • 2015-12-05
相关资源
最近更新 更多