正则表达式替换html属性中的所有引号?

时间:2016-11-19 14:55:56

标签: javascript regex

字符串示例:

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

目标:

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

我试过了:

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;') + '"';
});

比如我和正则表达式的noob我需要你的帮助:)

P.S。我们不能使用前瞻和放大lookbehind(javascript)

1 个答案:

答案 0 :(得分:2)

乍一看,我建议在 data-html =&#34;&#34; 值内的字符串上使用escape()函数。这会处理所有冲突的html字符。然后,当您从data-html读取值时,可以使用unescape()

请参阅解释escape()unescape()的以下链接:http://www.w3schools.com/jsref/jsref_unescape.asp

修改:JavaScript版本1.5中不推荐使用unescape()函数。请改为使用decodeURI()decodeURIComponent()http://www.w3schools.com/jsref/jsref_decodeuri.asp

示例:

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>';