Reputation: 326
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'))
Upvotes: 2
Views: 237
Reputation: 1
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
Upvotes: 0
Reputation: 4302
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>
Upvotes: 1
Reputation: 29172
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)
Upvotes: 1