【问题标题】:Can you ignore HTML in a string while doing a Replace with jQuery? [duplicate]在使用 jQuery 进行替换时可以忽略字符串中的 HTML 吗? [复制]
【发布时间】:2011-01-18 08:58:43
【问题描述】:

可能重复:
Replace words in a string, but ignore HTML

调用 Replace 时是否可以忽略 HTML 元素?

示例代码:

$myText.replace(new RegExp( $searchString, 'gi' ), 
    '<span class="highlight">'+ $searchString + '</span>');

$myText 是一大串 HTML 例如:

var $myText = 
    "<p>Lorem Ipsum is simply dummy text of the printing and typesetting " +
    "industry. Lorem Ipsum has been the industry's standard dummy text " +
    "ever since the 1500s, <img src="something">when an unknown printer " +
    "took a galley of type and scrambled it to make a type specimen book. " +
    "It has survived not only five centuries, " +
    "<a href="#" title="Lorem">but</a> also the leap into electronic " +
    "typesetting, remaining essentially unchanged. It was popularised in " +
    "the 1960s with the release of Letraset sheets containing Lorem Ipsum " +
    "passages, and more recently with desktop publishing software like " +
    "Aldus PageMaker including versions of Lorem Ipsum.</p>"

$searchString 等于用户在文本输入框中输入的任何内容。

如果是,根据上面的示例代码,我该怎么做?

【问题讨论】:

    标签: javascript jquery replace


    【解决方案1】:

    是的,看看下面的论坛帖子:

    http://forums.asp.net/t/1443955.aspx

    您正在寻找的 RegEx 模式类似于以下内容:

    "(?<!<[^>]*)Jon Doe(?<![^>]*<)"
    

    基本上,您是在对括号 之外的任何内容进行搜索和替换。

    JavaScript:

    phrase = phrase.replace(/"(?<!<[^>]*)Jon Doe(?<![^>]*<)" /i, "is not");
    

    【讨论】:

    • 在 jQuery 术语中,您可以按以下方式使用上述 RegEx 表达式:phrase = phrase.replace(/"(?]*)Jon Doe(?]*
    • 但不会有一个流浪 > 文本中的所有东西都乱七八糟吗?还是格式错误的 html,他们只是在一个实例中使用

      而在其他地方使用

      text

    • 不。您唯一忽略标签内的内容 - 不要忽略此this too>
    • 除非出于某种原因他们决定将 html 代码作为文本输入的一部分。
    • 我已经尝试了几次,不断收到来自 Firebug 的无效量词 ?]*)Jon Doe(?]*]*)Jon Doe(?]*'+ $searchString + '');
    【解决方案2】:

    用正则表达式解析 HTML? This isn't a good idea。我建议将 HTML 插入 DOM,然后遍历节点。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-26
      • 2019-06-30
      • 2012-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多