Reputation: 901
I want to check if a string (let entry)
contains exact match with let expect
:
let expect = 'i was sent'
let entry = 'i was sente to earth' // should return false
// let entry = 'to earth i was sent' should return true
// includes() using the first instance of the entry returns true
if(entry.includes(expect)){
console.log('exact match')
} else {
console.log('no matches')
}
There are lots of answers on StackOverflow but I can't find a working solution.
Note:
let expect = 'i was sent'
let entry = 'to earth i was sent'
should return true
let expect = 'i was sent'
let entry = 'i was sente to earth'
should return false
Upvotes: 3
Views: 16772
Reputation: 2036
Seems like you're talking about matching word boundary, which can be accomplished using \b
assertion in RegExp
which matches word boundary, so there you go:
const escapeRegExpMatch = function(s) {
return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
};
const isExactMatch = (str, match) => {
return new RegExp(`\\b${escapeRegExpMatch(match)}\\b`).test(str)
}
const expect = 'i was sent'
console.log(isExactMatch('i was sente to earth', expect)) // <~ false
console.log(isExactMatch('to earth i was sent', expect)) // <~ true
Upvotes: 8
Reputation: 71
I have not tested this but you need to convert the expected to an array of strings and then check if all items are in the entry string.
let arr = expect.split(" ");
if (arr.every(item => entry.includes(item)) {
console.log("match");
}
else.....
Upvotes: 2