2

I am currently using the Javascript Search() method to search for a match in a string. I want to find the closest match, for example, if the string is 'apple iphone', and a person searches 'iphone 6' I want there to be a match, but for some reason, the .search method doesn't work this way.

Is there a more efficient way to use this or another method that can be more useful?

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')) 
11
  • try using elastic search. It will return what you need with a relevance score as well Commented Sep 8, 2017 at 4:29
  • 2
    Also, if you don't care about the exact similarity and you just need to find any similar part you can use .split function. So your string will be split by space indicator and then you can use indexOf once for iphone 5, next time for iphone and lastly for 5 Commented Sep 8, 2017 at 4:40
  • 1
    The approach of @stdob-- is nice, it's like what I said. But something is missed in his approach, you have to check is there any iphone 5 or nuh then you would execute the reduce function. Commented Sep 8, 2017 at 5:00
  • 1
    You can also use test.search(term.split(/\s/).join('|')). Commented Sep 8, 2017 at 6:03
  • 1
    @HassanImam Your answer was super simple and exactly what I was looking for! Commented Sep 8, 2017 at 13:51

3 Answers 3

1

You can use below sample code.

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)

Sign up to request clarification or add additional context in comments.

Comments

1

Match two strings with the same word in JavaScript

From the answer above , I think the flowing code is what you are looking for :

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

Comments

0

If you mean searching something 'apple' OR 'iphone', use it as condition.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.