Ankit Shah Ankit Shah -4 years ago 203
Javascript Question

Javascript String Replace span element by empty string

I have HTML string in JS where I would like to remove the span element from it.

var HTML= '<div>test</div><p>test</p><span class="removedata">X</span><span>test</span><span class="removedata">X</span>';


After removing Span, it should be look like:

HTML= '<div>test</div><p>test</p><span>test</span>';


I have tried below JavaScript operation but does not work,

HTML = HTML.replace('/<span class="removedata">X</span>/g',"");


Any inputs?

Answer Source

The slash / is a special character in regular expressions and you need to escape it \/:

var html = '<div>test</div><p>test</p><span class="removedata">X</span><span>test</span><span class="removedata">X</span>';
var newHtml = html.replace(/<span class="removedata">X<\/span>/g, '');

console.log(newHtml); // "<div>test</div><p>test</p><span>test</span>"

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download