【问题标题】:jQuery find and replace ignoring tagsjQuery查找和替换忽略标签
【发布时间】:2017-01-08 17:14:21
【问题描述】:

我已经用 jQuery 构建了一个小的查找和替换功能。 (See functional example here) 在您考虑格式化标签之前,它运行良好。

假设以下html:

Here <i>is</i> my <b>sample</b> text

如果您搜索sample text,搜索会因为粗体标签而失败。

可接受的结果是删除&lt;b&gt;sample&lt;/b&gt; text,将其替换为您输入的任何替换内容。它应该单独留下斜体标签。这怎么可能实现?

这是我目前所拥有的:

function findandreplace() {
  var text = $('.editor').html(),
      find = $('#find').val(),
      replace = $('#replace').val(),
      newText = text.replace(new RegExp(find, "g"), replace)
  $('.editor').html(newText);
}

【问题讨论】:

  • 看看这个:jsfiddle.net/u6fef1eg/5你可以用斜体或粗体替换单词
  • @MoolsBytheway,似乎对我不起作用?为了清楚起见,我在搜索sample text时需要替换&lt;b&gt;sample&lt;/b&gt; text

标签: javascript jquery replace find


【解决方案1】:

您可以使用text() 忽略标签并替换文本,但不能保留标签。这是你想要的吗?

function findandreplace() {
  var text = $('.editor').text(),
      find = $('#find').val(),
      replace = $('#replace').val(),
      newText = text.replace(new RegExp(find, "g"), replace)
  $('.editor').html(newText);
}

编辑:这个满足要求,但是我们可以针对需要的标签进一步概括/优化它。

function findandreplace() {
     var find = $('#find').val(),
         replace = $('#replace').val()

     $('.editor').find('b').contents().unwrap();
     var text = $('.editor').html();
     var newText = text.replace(new RegExp(find, "g"), replace)
     $('.editor').html(newText);
}

【讨论】:

  • 搜索词组中的标签可以去掉,但其他标签必须保留。
  • 我很欣赏,但是这种方法有问题。例如,如果您有 here &lt;b&gt;is&lt;/b&gt; my &lt;b&gt;test&lt;/b&gt; 的代码并且您搜索“test”,它也会从单词“is”中去除粗体标记。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-07-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-19
  • 2021-06-01
相关资源
最近更新 更多