tags:

views:

38

answers:

3

I would like a way to replace the bracket text everywhere on a page with a link. I know this could be done serverside with php/etc, but I would be able to include this script to be able to simply be included and to handle the replacement itself.

For example:

If [page=12] is found within the page I would like to link it to: to change it to: http://www.example.com/pages/12 ( a clickable link ).

Thanks!

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

As for finding everywhere on the page, you don't really want to do this.

SilentGhost
A: 

Here's a regex to do it:

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

This will match [page=testing] as well.

Eric
+1  A: 

This works as I described in the comments:

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