3

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?

0

3 Answers 3

4

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>";
});
Sign up to request clarification or add additional context in comments.

4 Comments

If I wanted to replace all instance of periods, then I'd use "/./g"?
You should use \., because . matches all non-newline characters (a dot has a special meaning in RegExs).
/word/g is a Regular Expression which matches "word". /g tells the replace function to continue matching until no match can be found (the default behaviour is to stop at the first match).
@RobW oh right! I thought wrong about /g before then! Thank you very much.
3

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)

Comments

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

1 Comment

Note the use of text instead of another html word. Advantage is that &gt; will not be broken by replacement. It will instead be treated as > and still work in the end. Something lacking in mine and Rob's solutions. Possibly dangerous disadvantage is that &lt;span onmouseover="..."&gt; has the potential to introduce an XSS vulnerability, because the resulting text will be re-enstated as HTML <span onmouseover="...">. Therefore, this code should only be used if the original input is known to be safe.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.