David G
David G

Reputation: 96810

Converting text into a link with JavaScript returns an error

 function assert() {
     document.write.apply(document, arguments);   
    }

var testLink = "google.com";

    function makeIntoLink(link) {
        if (link.match(/^[a-zA-Z0-9]+(.com)/)) {
            link.replace(link, "<a href=\"http://www." + link+ "\">" + link + "<\/a>");
        }
        return link;
    }



    assert(makeIntoLink(testLink));

It writes it down but not in link form. Just "google.com" without the link. What could've gone wrong?

Upvotes: 0

Views: 72

Answers (4)

Martijn
Martijn

Reputation: 13622

As the others have said, replace doesn't change the variable, it just returns a new one. But in this case, you don't really want to replace something, you just want to concatenate some stuff around it.

IMO, you don't need the replace function for that:

function makeIntoLink(link) {
    if (link.match(/^[a-zA-Z0-9]+(.com)/)) {
        link = '<a href="http://www.' + link + '">' + link + '</a>';
    }
    return link;
}

(I've also removed your \" escapes by using different quote characters for the JS string literal and the HTML attributes. This makes it a mite less hard to read, IMHO).

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1074335

replace returns a version of the string with the replacement made; the string is not replaced in-situ. So link = link.replace... rather than simply link.replace.

Upvotes: 0

Karl Nicoll
Karl Nicoll

Reputation: 16419

A function like link.replace doesn't actually replace stuff inside the string, it actually returns a NEW string with the replacements made. For example:

function replaceText() {
    var searchText = ".com";
    var link = "google.com";

    var newLink = link.replace(searchText, ".co.uk");

    alert(link); // Output = "google.com"
    alert(newLink); // Output = "google.co.uk"

}

In your situation though, you don't need to use string.replace(...) at all, instead you can just do this:

function makeIntoLink(link) {
    if (link.match(/^[a-zA-Z0-9]+(.com)/)) {
        //link.replace(link, "<a href=\"http://www." + link+ "\">" + link + "<\/a>"); <-- OLD
        link = "<a href=\"http://www." + link+ "\">" + link + "<\/a>"; // <-- NEW
    }
    return link;
}

Upvotes: 1

Jim Blackler
Jim Blackler

Reputation: 23169

link.replace doesn't change the text in-situ, it makes a new string. Trying changing the line from link.replace(link... to link = link.replace(link...

Upvotes: 1

Related Questions