0

I am new to javascript but understand jQuery. I am trying to use this code to convert www. and http in p tags to working links.

Here is the code I am using, the problem is that I do not fully understand how the code works, could anybody please explain?

<script>
var re = /(http:\/\/[^ ]+)/g;

function createLinks(els) {
    $(els).contents().each(function () {
        if (this.nodeType === 1 && this.nodeName !== 'script') {
            createLinks(this);
        } else if (this.nodeType === 3 && this.data.match(re)) {
            var markup = this.data.replace(re, '<a href="$1">$1</a>');
            $(this).replaceWith(markup);
        }
    });
}

createLinks(document.body);
</script>
palaѕн
  • 72,112
  • 17
  • 116
  • 136
  • 3
    This question appears to be off-topic because it is about explaining existing code and should be on either http://programmers.stackexchange.com/ or http://codereview.stackexchange.com/ – Rory McCrossan Nov 07 '13 at 10:25
  • http://stackoverflow.com/questions/37684/how-to-replace-plain-urls-with-links – Manish Nov 07 '13 at 10:26

2 Answers2

1

First, you set regular expression template for matching text which starts from "http://"

Second, you create recursive function which traverse whole html document.

nodeType == 1 means that current element is html tag (i.e. a, p, div etc)

nodeType == 2 means that element is Attribute

nodeType == 3 means that element is text node

So when you found html tag, you're searching inside it, when you found text node, you are checking via regular expression, if this text starts from "http://", if so you change and replce this text to <a href="yourmatchedurl">yourmatchedurl</a>

in the end you call your function to start from body as a root

Roman
  • 179
  • 1
  • 1
  • 10
0

ok, here goes...

//create a regular expression to format the link 
var re = /(http:\/\/[^ ]+)/g;

//this is the create links function which gets called below, "els" is the elements passed to the function (document.body)
function createLinks(els) {

    //for each of the elements in the body
    $(els).contents().each(function () {

        //check if its an element type but not a script
        if (this.nodeType === 1 && this.nodeName !== 'script') {

            //call the create links function and send in this object
            createLinks(this);

        //if its not an element but is a text node and the format matches the regular expression
        } else if (this.nodeType === 3 && this.data.match(re)) {

            //create the markup
            var markup = this.data.replace(re, '<a href="$1">$1</a>');

            //finally, replace this link with the marked up link
            $(this).replaceWith(markup);
        }
    });
}
//call the create links function
createLinks(document.body);

I hope the commented code helps you understand.

wf4
  • 3,727
  • 2
  • 34
  • 45