David19801
David19801

Reputation: 11448

JS Replace characters with link?

If I have a block of text inside a div like:

<div id='t1'>
This is a great testing string.  Tomorrow grass is green.
</div>

and I want to replace all instance of the letter "g" with a link to google, like

<a href='www.google.com'>g</a>

Is it possible to do this with just Javascript/jquery?

Upvotes: 3

Views: 308

Answers (3)

Babak Bandpay
Babak Bandpay

Reputation: 177

$('#t1').html( $('#t1').text().replace(/g/g,"<a href='www.google.com'>g</a>") );

Upvotes: 1

Rob W
Rob W

Reputation: 348972

If you want to perform a simple string replacement, the following will do:

var div = document.getElementById("t1");
div.innerHTML = div.innerHTML.replace(/g/g, "<a href='http://www.google.com'>g</a>");

If you need more dynamics, e.g. substituting a word with a link, depending on the value, use:

Example: Replace g or G with different URLs:

var div = document.getElementById("t1");
var mapper = {
    g: "http://www.google.com",
    G: "http://stackoverflow.com"
};
div.innerHTML = div.innerHTML.replace(/[Gg]/g, function(fullmatch){
    return "<a href='" + mapper[fullmatch] + "'>" + fullmatch + "</a>";
});

Upvotes: 4

700 Software
700 Software

Reputation: 87773

No jQuery required.

var t1 = document.getElementById('t1')
t1.innerHTML = t1.innerHTML.replace(/g/g, '<a href="http://www.google.com/">g</a>')

In /g/g, the first g is what you are searching for. The second g means global (aka replace all)

Upvotes: 3

Related Questions