繁体   English   中英

使用jQuery替换和正则表达式替换字符串

[英]Using jQuery replace and regex to replace string

我目前正在使用.replace函数替换页面上的特定字符串。 鉴于我不知道当前字符串的位置,所以我无法选择它,我的代码看起来像这样:

$('body').html( $('body').html().replace(regex, 'sometext') );

所以如果页面最初看起来像这样:

<div class="a">Hello</div>

It now looks like this:

<div class="a">sometext</div>

有没有办法不使用$('body').html( $('body').html().replace() )

谢谢!

编辑:示例

<p class="last">Mac, iPhone, iPod and iPad customers within 90 days of ownership are eligible for complimentary phone support — one support incident per iPod and unlimited incidents per Mac, iPhone and iPad. <a href="/support/" onclick="s_objectID=&quot;http://www.apple.com/support/_3&quot;;return this.s_oc?this.s_oc(e):true">Online technical support</a> for Apple products is available beyond the initial 90 days.</p>

使用这个:

$('body').html( $('body').html().replace("iPhone", '<a href="#">iPhone</a>') );

它将取代iPhone的每个实例,使其看起来像iPhone

导致:

<p class="last">Mac, <a href="#">iPhone</a>, iPod and iPad customers within 90 days of ownership are eligible for complimentary phone support — one support incident per iPod and unlimited incidents per Mac, <a href="#">iPhone</a> and iPad. <a href="/support/" onclick="s_objectID=&quot;http://www.apple.com/support/_3&quot;;return this.s_oc?this.s_oc(e):true">Online technical support</a> for Apple products is available beyond the initial 90 days.</p>

您可以逐个节点地遍历DOM层次结构,检查文本节点,然后比较每个单独文本节点中的文本。 这将消除您当前代码可能导致的破损类型。 它可以避免像当前代码那样破坏所有事件处理程序。

仅供参考,这里是我为不同的答案写的不同功能的修改,可以做你想要的:

function replaceTextInDomTree(root, searchRegEx, replace) {
    var node = root.firstChild;
    while(node) {
        if (node.nodeType == 3) {
            if (searchRegEx.test(node.nodeValue)) {
                // we do the test first to avoid setting 
                // nodeValue when there's no change
                // to perhaps save the browser some layout time
                // since we'd be operating on every single text node
                node.nodeValue = node.nodeValue.replace(searchRegEx, replace);
            }
        }
        if (node.hasChildNodes()) {
            // go down into the children
            node = node.firstChild;
        } else {
            while (!node.nextSibling) {
                node = node.parentNode;
                if (node == root) {
                    return;
                }
            }
            node = node.nextSibling;
        }
    }
}

笔记:

1)这将替换连续文本块中的文本,但不包含HTML标记。

2)如果要在同一文本节点中进行多次替换,请确保将g标志放在传入的正则表达式中。

暂无
暂无

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

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