替换字符串,除非它在给定字符串的某个子字符串中

Replacing a string unless its in a certain substring of given string

给定一个长 html 字符串,我想替换 html 中的一个字符串,除非它在 ​​html 的 <img> 标签内。

例如, 输入:text "here"<img src="img_url.jpg" width="100" height="100"></img>

我想用 &quot; 替换所有出现的 ",除非引号在 <img> 标签内,因为那样会破坏 url。

输出:text &quot;here&quot;<img src="img_url.jpg" width="100" height="100"></img>

我目前使用的是 input.replace(/"/g, "&quot;"),但这会替换字符串中的所有引号。我如何替换除特定子字符串之外的所有内容?我对正则表达式不是很有经验,但我发现我可以使用 /<img[^>]+>/

检测 img 标签

非常感谢您的帮助!

假设所有属性都有效(即没有<内部属性,如<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 "&quot;";
});
snippet.log(str);
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

但是,只创建一个 DOM,然后遍历所有文本节点并在本地进行替换,然后再次序列化为 HTML 可能会更安全。 (编辑 ...正如 Arun P Johny 所做的那样,我会赞成)。

此外,我认为在 <img> 标签以外的所有内容中替换它是个坏主意,因为那样你可能会得到 <div class=&quot;red&quot;>.

之类的东西

使用正则表达式

替换 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, '&quot;');
  }
});

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>