2017-09-08 7 views
2

現在、Javascript Search()メソッドを使用して文字列内の一致を検索しています。 文字列が「apple iphone」で、人が「iphone 6」を検索して一致するような場合など、最も近い一致を探したいのですが、何らかの理由で.searchメソッドが機能しませんこちらです。Javascriptでより効率的に.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')) 
+0

弾性検索を使用してみてください。関連性スコアで必要なものを返す – TheChetan

+0

検索の代わりに、 '.match()'を使うことができます。https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match –

+2

また、正確な類似性を気にせず、同様の部分を見つける必要がある場合は、 '.split'関数を使用することもできます。あなたの文字列はスペースインジケータで分割され、次に 'iphone 5'、' iphone'と '5'のために' indexOf'を一度使うことができます。 –

答えて

1

以下のサンプルコードを使用できます。

const test = 'apple iphone' 
 

 
const term = 'iphone 5' 
 

 
// Split by whitespace 
 
const terms = term.split(/\s/) 
 

 
// Test all sub term 
 
const result = terms.reduce(function(previousValue, currentValue) { 
 
    if (test.search(currentValue) > -1) previousValue.push(currentValue) 
 
    return previousValue 
 
}, []) 
 

 
console.log(result.length > 0)

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> 
0

何か 'りんご' を検索する意味場合または「iphone」は、条件として使用します。

'iphone'.search(/apple|iphone/); //this doesn't return -1 
'iphone 5'.search(/apple|iphone/); //this doesn't return -1 
関連する問題