简体   繁体   English

jQuery查找并替换忽略标签

[英]jQuery find and replace ignoring tags

I've built a little find and replace function with jQuery. 我用jQuery构建了一些查找和替换功能。 ( See functional example here ) It works well until you consider formatting tags. 请参见此处的功能示例 )在考虑格式化标签之前,它可以很好地工作。

Assuming the following html: 假设以下html:

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

If you search for sample text , the search fails due to the bold tags. 如果您搜索sample text ,则搜索将由于加粗标签而失败。

The acceptable result would be removing <b>sample</b> text , replacing it with whatever you have entered for the replacement. 可接受的结果是删除<b>sample</b> text ,将其替换为您输入的替换内容。 It should leave the italic tag alone. 它应该不留斜体标签。 How could this be accomplished? 如何做到这一点?

Here's what I have so far: 这是我到目前为止的内容:

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

You can use text() to ignore the tags and replace the text, but cannot retain the tags. 您可以使用text()忽略标签并替换文本,但不能保留标签。 Is this you want? 这是你想要的吗?

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

Edit: This one satisfies the requirement, however we can generalize/optimize it further for required tags. 编辑:这可以满足要求,但是我们可以针对所需的标签进一步对其进行概括/优化。

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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM