【问题标题】:How to check if a string contains multiple words on different locations如何检查字符串是否在不同位置包含多个单词
【发布时间】:2014-04-30 20:51:45
【问题描述】:

所以我有多个这样的字符串:

字符串 1:那里这是我正在尝试做的一件事,但我不知道如何idea
字符串 2:我真的不知道如何修复它。
字符串 2:希望有人可以帮助我。

现在我还有一个字符串,它是一个可以是任何东西的搜索输入,例如:

有想法

当用户输入并发送我希望 JavaScript 也与字符串 1 匹配时。
我也想让它返回两个字符串匹配的字符数。

如果有人可以帮助我,我将不胜感激。

提前致谢,

工作

【问题讨论】:

    标签: javascript regex string search compare


    【解决方案1】:
    <script>
            $(document).ready(function () {
                var myTestValue = ['test1', 'test2', 'test3'];
    
                for (var i = 0; i < myTestValue.length; i++) {
                    if(window.location.href.indexOf(myTestValue[i]) > -1) {
                        alert("your contains the string "+myTestValue[i]);
                    }
                }
            });
    </script>
    

    我不知道它对你有没有帮助..但我希望你从 @Job Sturm 中得到想法

    【讨论】:

      【解决方案2】:

      如果你想知道比赛的长度,e.g. using regex:

      var str = "There idea";
      
      var pattern = new RegExp("\\b" + str.replace(/ +/g, "\\b.*\\b") + "\\b", "i")
      console.log(pattern)
      
      var strings = [
        "There is this one thing that I'm trying to do but I have no idea how",
        "I really have no clue how too fix it",
        "Hopefully maybe someone can help me"
      ]
      
      for( i=0; i < strings.length; i++ ) 
        if( res=strings[i].match(pattern) ) 
          console.log( res[0], res[0].length )
        

      \b 匹配 word boundary(零长度匹配)

      【讨论】:

      • 谢谢您,现在只有一个问题,我如何在该正则表达式中获取用户输入?
      • @JobSturm 查看更新的答案和fiddle,如果这就是您的意思。从 str 构建正则表达式,其中空格替换为 \b.*\b(边界、小丑、边界)
      • 类似,我喜欢这个,因为这个词可以按任何顺序排列。 stackoverflow.com/a/13911776/1223763
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-11
      相关资源
      最近更新 更多