Home > database >  javascript word in sentence matching
javascript word in sentence matching

Time:08-16

I'm currently trying to find matching words within sentences, and I have a method that mostly works. It's working on a HTMLNode.textContent where I currently use the indexOf method to find a match.

let exists = node.textContent.indexOf(x.searchText) > -1

I need it to match exactly, including any spaces and special characters in the word, which works with indexOf, but I also want to be able to create exceptions to this exact search.

For example the word "Burnett’s" should be equal to "Burnett's" despite the apostrophe formats being different.

There are quite a lot of checks when this runs, so preferably I want something fast without having to check every word if it contains either of those apostrophes and if so remove it so it's not part of the comparison. Are there any better ways to check for or do it on?

CodePudding user response:

You could replace every exception variant to a single one to check against:

function cleanText(str) {
    return str.replace(/[`’]/g,"'");
}
            
let exists = cleanText(node.textContent).indexOf(cleanText(x.searchText)) > -1;

You can easily chain additional exceptions in the cleanText function, for example:

function cleanText(str) {
    return str.replace(/[`’]/g,"'").replace(/@/g, " at ").replace(/&/g, " and ");
}
  • Related