给定一个长html字符串,我想替换html中的字符串,除非它在html的<img>
标签内。
例如,
输入:text "here"<img src="img_url.jpg" width="100" height="100"></img>
我想替换所有出现的&#34;使用"
除非引号位于<img>
标记内,因为这会破坏网址。
输出:text "here"<img src="img_url.jpg" width="100" height="100"></img>
我目前正在使用input.replace(/"/g, """)
,但它会替换字符串中的所有引号。如何替换除某个子串之外的所有内容?我对正则表达式不是很熟悉,但我发现我可以使用/<img[^>]+>/
检测img标签
非常感谢您的帮助!
答案 0 :(得分:2)
假设所有属性都有效(即内部属性没有<
,例如<img comparison="a<2">
):
var str = 'text "here"<img src="img_url.jpg" width="100" height="100"></img>';
str = str.replace(/(<.*?>)|"/g, function(m, m1) {
if (m1) return m1;
else return """;
});
snippet.log(str);
&#13;
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
&#13;
但是,创建一个DOM可能更安全,然后通过所有文本节点递归并在本地进行替换,然后再次序列化为HTML。 (编辑 ......正如Arun P Johny刚刚做的那样,我将会提出来。)
另外,我认为除了<img>
标签之外的所有内容都替换它是个坏主意,因为那样你可能会得到像<div class="red">
这样的东西。
答案 1 :(得分:2)
使用regex
替换html字符串的内容总是一个坏主意
var string = 'text "here"<img src="img_url.jpg" width="100" height="100"></img>';
var $tmp = $('<div />', {
html: string
});
$tmp.find('*').addBack().contents().each(function() {
if (this.nodeType == Node.TEXT_NODE) {
this.nodeValue = this.nodeValue.replace(/"/g, '"');
}
});
var result = $tmp.html();
snippet.log(result)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<!-- To show result in the dom instead of console, only to be used in the snippet not in production -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>