-1

I want to replace all the characters "<" and ">" with "<" and ">" respectively from a string.

I tried this code but it didn't worked for me -

// theMainString is the string from which I want the characters replaced

let theMainString = "<div>Hello World</div>";
let s1, s2;
s1 = (theMainString).replace("<", "&lt;");
s2 = s1.replace(">", "&gt;");
console.log(s2);

// Output: "&lt;div&gt;Hello World</div>"

Any help would be highly appreciated
CubeDev
  • 125
  • 2
  • 9

2 Answers2

1

Important to realize that replace() only finds first instance unless you use a regex with a g flag.

One simple approach is insert the string into a temporary element as text and retrieve it's innerHTML.

This way you let the dom parser figure out the various characters and return their html entities without having to catalog them yourself

let theMainString = "<div>Hello & World</div>";
let span = document.createElement('span');
span.innerText = theMainString;
console.log(span.innerHTML)
charlietfl
  • 170,828
  • 13
  • 121
  • 150
0

Through your code, the replace function only replace the first occurrence. If you use regex, you can just add an g option to replace the pattern globally.

let theMainString = "<div>Hello World</div>";
let s1, s2;
s1 = (theMainString).replace(/</g, "&lt;");
s2 = s1.replace(/>/g, "&gt;");
console.log(s2);
sam
  • 1,767
  • 12
  • 15