【问题标题】:Search for a whole word in a string在字符串中搜索整个单词
【发布时间】:2013-09-15 10:43:14
【问题描述】:

我正在寻找一个用 JavaScript(而不是 jQuery)编写的函数,如果给定的单词完全匹配(不应区分大小写),它将返回 true。

喜欢...

var searchOnstring = " Hi, how are doing?"

   if( searchText == 'ho'){
     // Output: false
   }

   if( searchText == 'How'){
     // Output: true
   }

【问题讨论】:

  • jQuery 是 JavaScript! (你想要的是不使用它。)
  • 如果是Howl 呢?
  • 我不想包含 jquery 库
  • 停止发布 indexOf() 答案!
  • @duffymo 我听到的最后一个人说类似的东西现在已经消失了 7 年...... :(

标签: javascript


【解决方案1】:

你可以使用正则表达式:

\bhow\b

例子:

/\bhow\b/i.test(searchOnstring);

如果你想要一个可变词(例如来自用户输入),你必须注意不要包含特殊的 RegExp 字符。

你必须转义它们,例如使用MDN中提供的函数(向下滚动一点)

function escapeRegExp(string){
  return string.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
}

var regex = '\\b';
regex += escapeRegExp(yourDynamicString);
regex += '\\b';

new RegExp(regex, "i").test(searchOnstring);

【讨论】:

  • 它显示如下错误:Uncaught TypeError: Object function RegExp() { [native code] } has no method 'escape'
  • @anand4tech 在调用我的代码之前,您必须包含该函数。 /谢谢门把手。
  • @anand4tech 查看我的编辑,我现在使用了 MDN 的转义功能。 /dystroy:谢谢。
  • @ComFreek, ---new RegExp(regex, "i").test(searchOnstring);---的值总是假的
【解决方案2】:

试试这个:

var s = 'string to check', ss= 'to';
if(s.indexOf(ss) != -1){
  //output : true
}

【讨论】:

    【解决方案3】:

    这是一个返回 true 的函数,其中 searchText 包含在 searchOnString 中,忽略大小写:

    function isMatch(searchOnString, searchText) {
      searchText = searchText.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
      return searchOnString.match(new RegExp("\\b"+searchText+"\\b", "i")) != null;
    }
    

    更新,如前所述,您应该转义输入,我正在使用来自https://stackoverflow.com/a/3561711/241294 的转义函数。

    【讨论】:

    • 这是一个仅链接的答案,不鼓励这样做。如果链接断开会发生什么?你的回答变得毫无用处。此外,我们不希望人们在到达 SO 后必须点击另一个链接。 -1
    • @poida 你应该转义searchText
    • 现在错了。你为什么还要检查null
    • 你试过了吗? (现在更好了,因为逃跑了。-1 被移除)
    • @poida 也删除了我的反对票,但应该真正将转义替换移动到一个函数中(我知道,这是相当风格的)。
    【解决方案4】:

    这样的事情会起作用:

    if(/\show\s/i.test(searchOnstring)){
        alert("Found how");
    }
    

    More on the test() method

    【讨论】:

    • 不匹配 That's how. 字符串
    • 不,他的意思是字符串"That's how."(或"How are you doing?"
    • 很公平,我对提供的字符串进行了测试,这是我的疏忽。
    • @faino:如果您提供了仅适用于预定义输入的解决方案 - 您可以将其替换为 return true;
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-22
    • 2011-12-27
    • 2021-03-31
    • 1970-01-01
    • 2016-04-26
    相关资源
    最近更新 更多