简体   繁体   中英

Regex that replace all quotes inside html attributes?

Example of string:

<a href="#" data-html="<input type="text" data-html="<input type="text">">"></a>

The target:

<a href="#" data-html="<input type=&quot;text&quot; data-html=&quot;<input type=&quot;text&quot;>&quot;>"></a>

I tried:

var string = '<a href="#" data-html="<input type="text" data-html="<input type="text">">"></a>';

string.replace(/"+(.?)"+/g, function(s) {
  return '"' + s.slice(1, s.length).slice(0, -1).replace(/"/g, '&quot;') + '"';
});

Such as I'm noob with regex I need your help :)

PS we can't use lookahead & lookbehind (javascript)

At first glance I would suggest to use the escape() function on the string inside your data-html="" value. This handles all conflicting html characters. Then when you read the vale from data-html you can use unescape() .

See the following link that explains escape() and unescape() : http://www.w3schools.com/jsref/jsref_unescape.asp

Edit: The unescape() function was deprecated in JavaScript version 1.5. Use decodeURI() or decodeURIComponent() instead: http://www.w3schools.com/jsref/jsref_decodeuri.asp

Example:

var strDataHtml_1 = encodeURI('<input type="text">')
var strDataHtml_2 = encodeURI('<input type="text" data-html="' + strDataHtml_1 + '">');
var string = '<a href="#" data-html="' + strDataHtml_2 + '"></a>';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM