ankur_agarwal
ankur_agarwal

Reputation: 62

Unescape HTML string till HTML content

I have a HTML string which may be escaped multiple times. I want to write a function in which i pass an escaped string and it returns the unescape string. The escaped string may be escaped n times.

For example, my escaped string is: -

%253Cp%253Ebbbbbbbbb%253C/p%253E%3Cinput%20type%3D%27hidden%27%20id%3D%27grid_7_domType%27%20class%3D%27allDomObjects%27%20datatype%3D%27subpart%27%3E  

If I unescape this string the first time then I will get:-

%3Cp%3Ebbbbbbbbb%3C/p%3E<input type='hidden' id='grid_7_domType' class='allDomObjects' datatype='subpart'>

Which is also an escaped string. So now I unescape this string again, and I get my original content:-

<p>bbbbbbbbb</p><input type='hidden' id='grid_7_domType' class='allDomObjects' datatype='subpart'>

Upvotes: 1

Views: 345

Answers (2)

Jaskaran Bindra
Jaskaran Bindra

Reputation: 3

For folks who want this solution in Angular 2+, there's a npm package which was born to do this.

npm install html-escape-unescape

Using this package, it's as simple as:

{{ someStringToBeUnescaped?times | unescape:'recursive' }}

It will continue to unescape the passed string until it can not be unescaped anymore and you get the HTML. Get it here.

Hope it helps someone.

Upvotes: 0

Robby Cornelissen
Robby Cornelissen

Reputation: 97331

You could just continue unescaping until your string no longer contains any escape sequences, i.e. it no longer matches /%[0-9A-F]{2}/.

var s = "%253Cp%253Ebbbbbbbbb%253C/p%253E%3Cinput%20type%3D%27hidden%27%20id%3D%27grid_7_domType%27%20class%3D%27allDomObjects%27%20datatype%3D%27subpart%27%3E";

while (s.match(/%[0-9A-F]{2}/i)) {
    s = unescape(s);
}

alert(s);

Probably better to use decodeURIComponent instead of unescape though.

Upvotes: 2

Related Questions