【问题标题】:Simple javascript find and replace简单的javascript查找和替换
【发布时间】:2011-08-24 10:19:41
【问题描述】:

是否有一种直接的方法可以在 div 中搜索特定字符串并将其替换为另一个字符串?我不能单独使用 .replaceWith ,因为 div 中还有其他元素需要保留。我尝试了这里找到的各种 javascript 方法,但均无济于事。

比如:

$('#foo').find('this string').replaceWith('this other string');

为:

<div id="foo"><div id="child">Other Element</div>this string</div>

谢谢。

【问题讨论】:

标签: javascript jquery replace


【解决方案1】:

String.replace(); 有什么问题?

例如

$("#div").html($("#div").html().replace("search string", "replace string"));

或爆炸:

var $divElement = $("#div");         //Find the div to perform replace on
var divContent = $divElement.html(); //Get the div's content
divContent = divContent.replace("search string", "replace string"); //Perform replace
$divElement.html(divContent);        //Replace contents of div element.

【讨论】:

    【解决方案2】:

    试试这个:

    var foo = $('#foo').html();
    
    foo = foo.replace('this string', 'this other string');
    
    $('#foo').html(foo);
    

    小提琴:http://jsfiddle.net/maniator/w9GzF/

    【讨论】:

    • “我需要保留 div 中的其他元素”——这不合适
    • 如果您多次出现“此字符串”,这将不起作用。
    • 像这样设置 html(..) 将重新创建 DOM 元素,这意味着您将丢失之前附加在这些元素上的任何数据或事件。
    • @Anurag 我认为没有其他方法可以做到这一点。为了保留处理程序,我会说使用live()
    • 是的,您绝对可以使用live()delegate()。我已经完成了这个确切的场景,这就是我必须做的。
    【解决方案3】:

    这会替换所有出现的情况:

    var $foo = $('#foo'),
        fooHtml = $foo.html();
    
    $foo.html(fooHtml.replace(/this string/g, 'this other string'));
    

    【讨论】:

    • 什么是?我的答案还是你答案中的 cmets?
    • 这个答案和我的一样,但还有更多ups
    • 因为它是正确的?你得到了复选标记,你的甚至没有替换每次出现的“这个字符串”。你在乎什么?
    【解决方案4】:

    这是我刚刚编写的一个 jQuery 插件,它为集合提供 safeReplace

    (function($){
    
    $.fn.safeReplace = function ( find, replacement ) {
    
        return this.each(function(index, elem) {
    
            var
                queue = [elem],
                node,
                i;
    
            while (queue.length) {
    
                node = queue.shift();
    
                if (node.nodeType === 1) {
                    i = node.childNodes.length;
                    while (i--) {
                        queue[queue.length] = node.childNodes[i];
                    }
                } else if (node.nodeType === 3) {
                    node.nodeValue = node.nodeValue.replace( find, replacement );
                }
            }
    
        });
    };
    
    })(jQuery);
    

    这是你如何使用它的:

    $('#foo').safeReplace( /this string/g, 'something else' );
    

    我只在 FF 4 中进行了测试,并且仅在示例 HTML 输入中进行了测试 - 建议进行更多测试。

    希望这会有所帮助!

    【讨论】:

      【解决方案5】:

      这个工作与您的术语出现的次数一样多,并且不会杀死任何不应更改的重要内容(存储在 excludes 数组中)。

      用法:findAndReplace('dog','cat', document.getElementById('content'));

      /* js find andreplace Based on http://james.padolsey.com/javascript/find-and-replace-text-with-javascript/ */
      
      function findAndReplace(searchText, replacement, searchNode) {
      if (!searchText || typeof replacement === 'undefined') {
          return;
      }
      var regex = typeof searchText === 'string' ?
                  new RegExp(searchText, 'g') : searchText,
          childNodes = (searchNode || document.body).childNodes,
          cnLength = childNodes.length,
          excludes = ['html','head','style','link','meta','script','object','iframe'];
      while (cnLength--) {
          var currentNode = childNodes[cnLength];
          if (currentNode.nodeType === 1 &&
            excludes.indexOf(currentNode.nodeName.toLowerCase() + ',') === -1) {
            arguments.callee(searchText, replacement, currentNode);
          }
          if (currentNode.nodeType !== 3 || !regex.test(currentNode.data) ) {
              continue;
          }
          var parent = currentNode.parentNode,
              frag = (function(){
                  var html = currentNode.data.replace(regex, replacement),
                      wrap = document.createElement('div'),
                      frag = document.createDocumentFragment();
                  wrap.innerHTML = html;
                  while (wrap.firstChild) {
                      frag.appendChild(wrap.firstChild);
                  }
                  return frag;
              })();
          parent.insertBefore(frag, currentNode);
          parent.removeChild(currentNode);
      }
      }
      

      【讨论】:

        【解决方案6】:

        只需使用 html().replace() 来匹配所有结果元素属性或标签名称。

        我也面临这个问题,我的解决方案类似于 http://james.padolsey.com/javascript/find-and-replace-text-with-javascript/ 中的 findAndReplace() 函数,但使用正则表达式来获取所有 textNode 并在其中进行搜索。

        function epubSearch(query) {
            var d = document.getElementsByTagName("body")[0];
            var re = new RegExp(query, "gi");//pattern for keyword
            var re0 = new RegExp("[>][^><]*[><]", "gi");//pattern to get textnode
        
            d.innerHTML = d.innerHTML.replace(re0, function (text) {
                // with each textNode, looking for keyword
                return text.replace(re, "<span class=\"search-result\" style=\"background-color:red;\">$&</span>");
            });
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2013-07-24
          • 1970-01-01
          • 2014-01-22
          • 1970-01-01
          • 2021-06-01
          • 2016-03-04
          • 2012-11-04
          • 1970-01-01
          相关资源
          最近更新 更多