Search code examples
jqueryhtmlstrip

How to strip html tags in string then escape the plain string and put the escaped string into html tags back


I wanted to strip html tags then escape plain string and put back the escaped string back into html tags , for that i have tried :

var aa = "<p>hi testing & </p>";
var bb = $(aa).text();
var cc = escape(bb);
var dd = aa.replace(bb, cc);

dd gives me the output "<p>hi%20testing%20%26</p>" , but the problem is when i have multiple html tags in string for eg: aa ="<p>hi testing & </p><p> failed & </p>" its not working.

Please help.

Thanks in advance.


Solution

  • You were close! jQuery.text() is quite handy for this. When you pass it a function it'll replace the text content of selected elements with the result of the function:

    var aa  = "<p>hi testing & </p><p> failed & </p>"
      , $aa = $(aa).text(function(_, content) { return escape(content); })
    ;
    
    console.log($aa);
    // => [<p>​hi%20testing%20%26%20​</p>​, <p>​%20failed%20%26%20​</p>​]