【问题标题】:Replacing a string unless its in a certain substring of given string替换字符串,除非它在给定字符串的某个子字符串中
【发布时间】:2015-07-14 03:38:00
【问题描述】:

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

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

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

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

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

非常感谢您的帮助!

【问题讨论】:

  • 您能否提供更多关于您如何使用它的背景信息?这些双引号最初是如何出现的?

标签: javascript jquery regex string substring


【解决方案1】:

假设所有属性都有效(即属性内没有<,如<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 刚刚所做的那样,我会赞成)。

另外,我认为在除&lt;img&gt; 标签之外的所有内容中替换它是一个坏主意,因为那样你可能会得到&lt;div class=&amp;quot;red&amp;quot;&gt; 之类的东西。

【讨论】:

    【解决方案2】:

    使用正则表达式替换 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>

    【讨论】:

    • $tmp.find('*').addBack().contents()$tmp.contents()不一样吗?
    • @Ja͢ck 在给定的标记中......但如果有多级元素,那么它将推迟......所以我通常选择这种风格
    猜你喜欢
    • 2020-10-04
    • 2020-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-18
    • 2012-04-03
    • 2013-07-23
    相关资源
    最近更新 更多