-3

CODE:

var searchedTerm = "test";
var returnedString = "National testing Plant testers";
var replacedString = returnedString.replace(/\searchedTerm/g, '<span class="highlight">'+searchedTerm+'</span>');

In other words I'm after replacing a searched string, from a returned longer string, to highlight wherever the searched string matched the returned one. Keeping in mind to highlight if it matches more than once in the same returned string aka global.

Pranav C Balan
  • 106,305
  • 21
  • 136
  • 157
Joe Borg
  • 65
  • 1
  • 12
  • Something like this? http://stackoverflow.com/questions/31275446/how-to-wrap-part-of-a-text-in-a-node-with-javascript – nhahtdh Oct 26 '15 at 09:11
  • Use `RegExp` constructor, `var regex = new RegExp(searchedTerm, 'g'); var replacedString = returnedString.replace(regex, '' + searchedTerm + ''); ` – Tushar Oct 26 '15 at 09:12

1 Answers1

1

Use RegExp() for converting search string to regex

var searchedTerm = "test";
var returnedString = "National testing Plant testers";
var replacedString = returnedString.replace(new RegExp(searchedTerm, 'g'), '<span class="highlight">' + searchedTerm + '</span>');

document.write(replacedString);
.highlight {
  color: red;
}
Pranav C Balan
  • 106,305
  • 21
  • 136
  • 157