I am highlighting words in search results by using the query that user enters. Some of the results contain symbols like apostrophes and I would like to make the highlighting work if the apostrophe is entered or not. So, if I have this search result
Patrick O'Hagan
And user enters
O'Hagan
Or
Ohagan
It should match the highlighted part: Patrick O'Hagan
One way to achieve this that I thought of was to build a regex by insert a not required apostrophe after each character that user entered, so query ohagan would be translated to this regex:
/(o[']?h[']?a[']?g[']?a[']?n[']?)/gi
This works but there must be a better way?
EDIT: Example I provided previously was not clear, so I will just provide an example code that should show what I want to achieve:
var resultText = 'Patrick O\'Hagan';
var query1 = 'o\'hagan';
var query2 = 'ohagan';
var regex1 = this.buildRegex(query1);
var regex2 = this.buildRegex(query2);
var highlightedText1 = resultText.replace(regex1, x => `<b>${x}</b>`);
var highlightedText2 = resultText.replace(regex2, x => `<b>${x}</b>`);
console.log(highlightedText1); //prints: Patrick <b>O'Hagan</b>;
console.log(highlightedText2); //prints: Patrick <b>O'Hagan</b>;
What I am looking for is the buildRegex
function which would construct a regular expression that would match the query in resultText
but would ignore the apostrophes.