views:

57

answers:

3

Hi people,

How can you use JQuery to find URLs within some text and automatically convert them into an actual hyperlink?

Example text,

var TextMemo = "This is some random paragraph text, but i mention a link to a website here. www.stackoverflow.com and another one here this time with http (http://www.google.co.uk)"

Is this a simple task?

Many thanks, Kohan

+1  A: 

how about this solution: http://stackoverflow.com/questions/37684/replace-url-with-html-links-javascript

John Boker
Looks exactly what i asked. I'll delete this. Many thanks. (I did search i promise)
Kohan
why the down vote?
John Boker
Wasn't me, have another +1. - Helped me out. And didn't need an explanation.
Kohan
@kohan thanks!!
John Boker
A: 

Firstly, it won't be as simple as replacing text in a single string because a typical paragraph will be made up of one or more text and element nodes which need to be traversed properly in order to effectively wrap the desired piece of text. You shouldn't be getting the text with something like innerText/textContent or innerHTML.

Try this:

var para = jQuery('#my-para')[0];

findMatchAndReplace(
    para,
    /\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|]/i,
    '<a href="$&">$&</a>'
);

Using this function:

function findMatchAndReplace(node, regex, replacement) {

    var parent,
        temp = document.createElement('div'),
        next;

    if (node.nodeType === 3) {

        parent = node.parentNode;

        temp.innerHTML = node.data.replace(regex, replacement);

        while (temp.firstChild)
            parent.insertBefore(temp.firstChild, node);

        parent.removeChild(node);

    } else if (node.nodeType === 1) {

        if (node = node.firstChild) do {
            next = node.nextSibling;
            findMatchAndReplace(node, regex, replacement);
        } while (node = next);

    }

}
J-P
A: 

Have a look at this one: http://stackoverflow.com/questions/247479/jquery-text-to-link-script

Hypnos