I have a JavaScript String which looks like this:
From Windows to Linux
With JavaScript, how can I highlight the words From and Linux, via a substring which looks like this:
From Linux
so the string looks like this in the end:
<mark>From</mark> Windows to <mark>Linux</mark>
This is my current implementation of the function to do that job:
function highlightSearchTerm(string, substring) {
const regex = new RegExp(`(${substring})`, 'ig');
return string.replace(regex, '<mark>$1</mark>');
}
I call it like this:
highlightSearchTerm("From Windows to Linux", "from linux")
It works well, the only thing that is missing is to make it work when the substring has words which are not directly next to each other.
These substrings for instance work:
- from windows
- From
- to Linux
While these don't (Words are not directly next to each other in the main string):
- Windows Linux
- from To
- Linux from
highlightSearchTerm?highlightSearchTerm("From Windows to Linux", "from linux")for example. I use svelte, so in the end the returned value just gets displayed as HTML.highlightSearchTerm("From windows to linux", "from|linux")and lmk if that works