-1

How can i replace two characters in multiple elements? I have found an answer using jquery but I am searching for vanilla js.

I want to replace < with &lt and > with &gt.

I tried it by myself but it only replaced first of these symbols.

let string = data.val().message;
string = string.replace("<", "&lt").replace(">", "&gt");

// <div>1</div> result was &ltdiv&gt1</div>

it only replaced the first symbols.

The element with symbols to replace has a class of .msgContent.

pilchard
  • 12,414
  • 5
  • 11
  • 23
kndxiu
  • 1
  • 2
  • 2
    Visit the [help center](https://stackoverflow.com/help), take the [tour](https://stackoverflow.com/tour) to see what and [How to Ask](https://stackoverflow.com/questions/how-to-ask). Show what you have tried and where you are stuck. When practical post a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example) of your attempt, noting input and expected output. – pilchard May 14 '22 at 11:46
  • 2
    This sounds like you're using the wrong tool for the job, but without specific information (where are you getting the string from, and what exactly are you doing with it), as well as the points raised by pilchard - above - we don't have enough information to answer your question. – David Thomas May 14 '22 at 11:49
  • 1
    So you tried something that did not work. Post your attempt and will will see what went wrong, so that we can suggest solutions. – Gabriele Petrioli May 14 '22 at 11:49
  • 1
    As a guess it looks like you're using [`replace()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace) but need [`replaceAll()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll) see: [How to replace all occurrences of a string in JavaScript](https://stackoverflow.com/questions/1144783/how-to-replace-all-occurrences-of-a-string-in-javascript) – pilchard May 14 '22 at 11:51
  • @GabrielePetrioli let string = data.val().message; string = string.replace("<", "&lt").replace(">", "&gt"); and some lines under: '
    \n' + ''+string+'' + '
    \n' +
    – kndxiu May 14 '22 at 11:59
  • See the duplicate – pilchard May 14 '22 at 12:04
  • 1
    @pilchard omg ty, it worked. i didnt see replaceAll snipped in vscode so i have no clue that can work. thanks – kndxiu May 14 '22 at 12:09

1 Answers1

0

Here's how you would do it with VanillaJS using regex.

var elems = document.querySelectorAll(".class");
elems.forEach(function (elem)
{
  var msg = elem.innerHTML.replace(/</g,"&lt").replace(/>/g,"&gt");
  elem.innerHTML = msg;
  console.log(msg); // Just for illustration purpose
});
<div class="class">
  <div>Some Meessage One</div>
</div>
<div class="class">
  <div>Some Meessage Two</div>
</div>
Mosia Thabo
  • 4,009
  • 1
  • 14
  • 24