'about replace methods in string in js

let code = document.querySelector('.Nform').innerHTML;
localStorage.setItem('code',JSON.stringify(code));
let finalCode = code.replace(/ <p class="removeElement" onclick="removeElement()"></p> /g , ` ` );
console.log(finalCode);
document.querySelector('.code').value =`${finalCode}`;

Hello , I want to use / /g to replace this html element from code but p tag have close element (/p) so how can escape it make sure i want to send this by code no sting, thanks



Solution 1:[1]

In your regex, You have to escape these four special characters : ", (, ), /

Demo :

let originalCode = document.querySelector('.Nform').innerHTML;

console.log(originalCode);

let finalCode = originalCode.replace(/<p class=\"removeElement\" onclick=\"removeElement\(\)\">Paragraph 1<\/p>/g, '');

console.log(finalCode);
<div class="Nform">
  <p class="removeElement" onclick="removeElement()">Paragraph 1</p>
  <p>Paragraph 2</p>
</div>

Solution 2:[2]

I think it's because of the parentheses, they should be escaped too. please try this: let finalCode = code.replace(/</div>/g, ' '); –

by GrafiCode https://stackoverflow.com/users/5334486/graficode

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Rohìt Jíndal
Solution 2 Ahmed Essam