如何在Javascript中更有效地使用.search()方法?

时间:2017-09-08 04:21:30

标签: javascript string search

我目前正在使用Javascript Search()方法在字符串中搜索匹配项。 我想找到最接近的匹配,例如,如果该字符串是' apple iphone',并且一个人搜索“iphone 6'我希望有匹配,但由于某种原因,.search方法不会这样做。

有没有更有效的方法来使用这个或其他更有用的方法?

const test = "apple iphone"
// this doesn't return -1 indicating there was a match
console.log(test.search('iphone'))

// this returns -1 indicating there wasn't any match at all despite there 
// being the word "iphone" in there 
console.log(test.search('iphone 5'))

3 个答案:

答案 0 :(得分:1)

您可以使用以下示例代码。

service.something

答案 1 :(得分:1)

Match two strings with the same word in JavaScript

从上面的答案中,我认为流动的代码就是你要找的东西:

<script>
 var m = "apple iphone".split(' ');
   var n = "iphone 6".split(' ');
      var isOk=0;

    for (var i=0;i<m.length;i++)
 {
    for (var j=0;j<n.length;j++)

 {
    var reg = new RegExp("^"+m[i]+"$", "gi");

  if (n[j].match(reg) )
   {isOk=1;break;}
          }
        }

     if (isOk==1)
       alert("match");

 </script>

答案 2 :(得分:0)

如果你的意思是搜索某些东西&#39; apple&#39; &#39; iphone&#39;,将其用作条件。

'iphone'.search(/apple|iphone/);    //this doesn't return -1
'iphone 5'.search(/apple|iphone/);   //this doesn't return -1
相关问题