0

Im trying to replace words in a string which may have html tags or spaces. So if I want to find/replace Javascript:

var text = 'Java Javascript and <li>Javascript</li> javascript';
var find = "Javascript"; 

var regex = new RegExp(`(?:>|\s)(${find})(?:<|\s)`, "gi");
var result = text.replace(regex, 'JavascriptUpdated');

console.log(result, "result");

However its not finding the char space version and I dont want to replace "<" just allow it to find.

Im using "\s" to no find inside words, so if search was "Java" I dont want to find that in inside "Javascript"

Slai
  • 22,144
  • 5
  • 45
  • 53
CerIs
  • 527
  • 3
  • 6
  • 14

2 Answers2

0

Here you can manually replace your string using search() method .

var text = 'Java Javascript and <li>Javascript</li> javascript';
var find = "Javascript"; 
var toUpdate = "javascriptUpdated";
var regex = /(<li> *|<li>)/g;

var index = text.search(regex); //search the index where regex got match . 
text = text.substr(0, index + 4) + toUpdate + text.substr(index + 13); //replacing the string manually .

console.log(text, "result"); //your result . 

You can see my running code . If you have any doubt , feel free to ask .

Pushprajsinh Chudasama
  • 7,772
  • 4
  • 20
  • 43
0

First, see the first comment above... parsing HTML is bad news. That said, if you know there are constraints then you should be ok (he said maniacally).

There's a couple ways to do this, but the most minimal changes to your code probably just need to be the regex and then using capture groups (and their indices) in the replacement.

var text = 'Java Javascript and <li>Javascript</li> javascript';
var find = "Javascript"; 

// notice capture groups for the angle brackets and spaces
var regex = new RegExp(`(>\s*)(${find})(\s*<)`, "gi");
// notice the use of $1 and $3 in here to reuse the > and < characters (and spaces)
var result = text.replace(regex, '$1JavascriptUpdated$3');

console.log(result, "result");
Jordan Kasper
  • 13,153
  • 3
  • 36
  • 55