Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using jquery or JS how do you turn a string into a link?

So I have a piece of HTML that looks something like this...

<p>This is some copy. In this copy is the word hello</p>

I want to turn the word hello into a link using jquery.

<p>This is some copy. In this copy is the word <a href="">hello</a></p>

That in itself is not too hard. My problem is that if the word is already apart of a link like the example below...

<p>In this copy is the <a href="">word hello</a></p>

I don't want that to end up with a link within a link...

<p>In this copy is the <a href="">word <a href="">hello</a></a></p>

Any help would be much appreciated.

like image 849
Paul Boag Avatar asked Oct 10 '12 14:10

Paul Boag


People also ask

How can create href link in jquery?

JavaScript Code: ready(function(){ $('#button1'). click(function(){ $(". link"). attr('href','https://www.w3resource.com/'); }); });

What is link JS?

JavaScript String link() String link() is deprecated in JavaScript. Avoid using it. It may cease to work in your browser at any time. The link() method returns a string embedded in an <a> tag: <a href="url">string</a>

Is a link a string?

In JavaScript, link() is a string method that is used to create the HTML <a> element with a hyperlink.


1 Answers

A little regex should do the trick (Update, see below):

$(document).ready(function(){
    var needle = 'hello';
    $('p').each(function(){
        var me = $(this),
            txt = me.html(),
            found = me.find(needle).length;
        if (found != -1) {
            txt = txt.replace(/(hello)(?!.*?<\/a>)/gi, '<a href="">$1</a>');
            me.html(txt);
        }
    });
});

Fiddle: http://jsfiddle.net/G8rKw/

Edit: This version works better:

$(document).ready(function() {
    var needle = 'hello';
    $('p').each(function() {
        var me = $(this),
            txt = me.html(),
            found = me.find(needle).length;
        if (found != -1) {
            txt = txt.replace(/(hello)(?![^(<a.*?>).]*?<\/a>)/gi, '<a href="">$1</a>');
            me.html(txt);
        }
    });
});

Fiddle: http://jsfiddle.net/G8rKw/3/

Edit again: This time, "hello" is passed as a variable to the regex

$(document).ready(function() {
    var needle = 'hello';
    $('p').each(function() {
        var me = $(this),
        txt = me.html(),
        found = me.find(needle).length,
        regex = new RegExp('(' + needle + ')(?![^(<a.*?>).]*?<\/a>)','gi');
        if (found != -1) {
            txt = txt.replace(regex, '<a href="">$1</a>');
            me.html(txt);
        }
    });
});

Fiddle: http://jsfiddle.net/webrocker/MtM3s/

like image 73
Tom Avatar answered Sep 27 '22 18:09

Tom