javascript - 如何删除特定文本短语的所有实例?

标签 javascript dom

在网页的正文区域是唯一可访问的部分的情况下,是否有办法使用内联 JavaScript 或其他支持内联的语言删除特定文本短语(以 HTML 编写)的所有实例?

这在很多情况下都很有用,例如人们使用 Tiny.cc/customurl 并希望删除声明“tiny.cc/”的部分


如果细节允许,我们将使用 Tiny.cc 修改日历插件以创建自定义 URL (tiny.cc/customurl)。该插件默认显示完整的 URL,所以我们想去掉文本“tiny.cc/”并在我们的代码中保留“customurl”部分:

<div class="ews_cal_grid_custom_item_3">
  <div class="ews_cal_grid_select_checkbox_clear" id="wGridTagChk" onclick="__doPostBack('wGridTagChk', 'tiny.cc/Baseball-JV');" >&nbsp;</div>
                            tiny.cc/Baseball-JV
  </div>

我们要删除的部分是第 3 行的 http://tiny.cc/ 本身。

最佳答案

要在不替换所有 HTML(这会破坏所有事件处理程序)的情况下执行此操作并且在不使用递归(通常更快)的情况下执行此操作,您可以这样做:

function removeText(top, txt) {
    var node = top.firstChild, index;
    while(node && node != top) {
        // if text node, check for our text
        if (node.nodeType == 3) {
            // without using regular expressions (to avoid escaping regex chars),
            // replace all copies of this text in this text node
            while ((index = node.nodeValue.indexOf(txt)) != -1) {
                node.nodeValue = node.nodeValue.substr(0, index) + node.nodeValue.substr(index + txt.length);
            }
        }
        if (node.firstChild) {
            // if it has a child node, traverse down into children
            node = node.firstChild;
        } else if (node.nextSibling) {
            // if it has a sibling, go to the next sibling
            node = node.nextSibling;
        } else {
            // go up the parent chain until we find a parent that has a nextSibling
            // so we can keep going
            while ((node = node.parentNode) != top) {
                if (node.nextSibling) {
                    node = node.nextSibling;
                    break;
                }
            }
        }
    }
}​

此处的工作演示:http://jsfiddle.net/jfriend00/2y9eH/

要对整个文档执行此操作,您只需调用:

removeText(document.body, "http://tiny.cc/Baseball-JV");

关于javascript - 如何删除特定文本短语的所有实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12077696/

相关文章:

javascript - 检查所有 radio 组是否已选中

javascript - Jquery解除绑定(bind)事件

javascript - 如何在不使用 'div' 条件的情况下将数组值拆分并添加到不同的 "if"组件中?

jQuery - $(some_element) 是否存在于 $(this) 和 $(this).closest(container) 之间?

javascript - Ext js 4.2 销毁组件

node.js - Electron - 如何将 html 文件加载到当前窗口?

javascript - c3js d3 dash-stroke 仅在 rect 元素的一侧

javascript - 防止页面卸载、失败。有想法吗?

javascript - 如何从 Javascript 对象的数组中选取数据并将其插入到对象的另一个数组中?

javascript - 如何通过书签将div添加到网页?