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

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

比如我对正则表达式很菜鸟,我需要你的帮助:)

附注我们不能使用lookahead &lookbehind (javascript)

最佳答案

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

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

编辑: unescape() 函数在 JavaScript 版本 1.5 中已被弃用。使用 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>';

关于javascript - 替换 html 属性内所有引号的正则表达式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40694261/

相关文章:

Mysql REGEXP 'o' 或 'aw'

regex - htaccess 正则表达式目录到变量

javascript - 我没有在React项目中定义for循环

javascript - 使用 Javascript/Jquery 对列表进行编号

javascript - 增加数量有更好的方法吗?

regex - 如何在 Linux 中将正则表达式传递给 find 命令?

Javascript 部分搜索

javascript - 使用 javascript 重写特定链接,但指向特定目录的链接除外

mysql - 使用正则表达式解析 ruby​​ 中的 SHOW ENGINE INNODB STATUS

c++ - boost::regex 中的嵌套量词