使用JS更改包含特定页面链接的括号内文本

时间:2009-10-01 14:22:49

标签: javascript

我想用链接替换页面上任何位置的括号文本。我知道这可以通过php / etc在服务器端完成,但我可以包含这个脚本,只需要包含并处理替换本身。

例如:

如果在页面中找到[page = 12],我想将其链接到: 将其更改为: http://www.example.com/pages/12(可点击链接)。

谢谢!

3 个答案:

答案 0 :(得分:1)

这就像我在评论中描述的那样工作:

var stack = [Array.prototype.slice.call(document.getElementsByTagName("body")[0].childNodes)], nodes, node, parent, text, offset;
while (stack.length) {
    nodes = stack.pop();
    for (var i=0, n=nodes.length; i<n; ++i) {
        node = nodes[i];
        switch (node.nodeType) {
            case Node.ELEMENT_NODE:
                if (node.nodeName.toUpperCase() !== "SCRIPT") {
                    stack.push(Array.prototype.slice.call(node.childNodes));
                }
                break;
            case Node.TEXT_NODE:
                text = node.nodeValue;
                offset = text.indexOf("[page=");
                if (offset >= 0 && text.substr(offset).match(/^(\[page=(\d+)\])/)) {
                    parent = node.parentNode;
                    var before = document.createTextNode(text.substr(0, offset));
                        link = document.createElement("a"),
                        after = document.createTextNode(text.substr(offset + RegExp.$1.length));
                    link.appendChild(document.createTextNode(text.substr(offset, RegExp.$1.length)));
                    link.setAttribute("href", "http://www.example.com/pages/" + RegExp.$2);
                    parent.insertBefore(after, node);
                    parent.insertBefore(link, after);
                    parent.insertBefore(before, link);
                    parent.removeChild(node);
                    stack.push([after]);
                }
        }
    }
}

答案 1 :(得分:0)

text.replace(/\[page=(\w+)\]/g, '<a href="http://example/pages/$1">http://example/pages/$1</a>')

至于在页面的任何地方找到 ,你真的不想这样做。

答案 2 :(得分:0)

这是一个正则表达式:

var str = "This is a link: [page=12]"

str = str.replace(/\[page=([^\]]*)\]/g,
    '<a href="www.example.com/pages/$1">www.example.com/pages/$1</a>');

这也符合[page = testing]。