-1

I was trying for some time to write a js function that will highlight (bold) every occurance of the searched text in the string that contain html tags.

Example: imagine that the string is

<b>test string</b> -- Bette <b>Higgins</b>

If I search for a character 'b', the result should be

<b>test string</b> -- <b>B</b>ette <b>Higgins</b>

(as you can see every occurrence of B should be surrounded with the html bold tag.

I tried using various regex expressions without success.

Any idea?

Thank you

gospodin
  • 952
  • 3
  • 17
  • 38
  • 2
    Did you search about it? I'm sure a lot of questions on this issue exist. – revo May 17 '18 at 09:25
  • if in general, like a well known answer on SO shows (https://stackoverflow.com/a/1732454/521598), you really can't have a reliable way to parse HTML with regex, maybe for your case you can try to adapt to JS this one https://stackoverflow.com/q/7891771/521598 – mishu May 17 '18 at 09:28
  • yes I searched a lot in SO but with every solution my first (opening tag containing text) is also highlighted. Just to be clear, I am not searching for a regex solution, any solution will be appreciated – gospodin May 17 '18 at 09:31

1 Answers1

0

You could reconstruct the string inside the element and on every occurence of "SearchTerm" surround with tag.

var str = "Hi, how's it going?"
var result = "";
var searchTerm = "it";
for (var i = 0; i <= str.length - searchTerm.length; i++) {
  if(str.substring(i, i + searchTerm.length) == searchTerm){
    result += "<b>" + str.substring(i, i + searchTerm.length) + "</b>";
    i += searchTerm.length - 1;
  } else {
    result += str.charAt(i)
  }
}
console.log(result);

Hope this helps.

George K
  • 468
  • 2
  • 13
  • Hi, thank you for your response but this is going to replace every occurrence (even the one in the html tabs, style attribute,..) of the searched text right? I should not replace the occurrences that are in html tags. – gospodin May 17 '18 at 09:44
  • It depends what string you pass to it. Do you need it to bypass content within html tags? – George K May 17 '18 at 09:51