Rich-text Reply

Find all instances of one word, and add a hyperlink. Code suggestions?

dlovin123 09-17-15

Find all instances of one word, and add a hyperlink. Code suggestions?

[ Edited ]

I want to see if it is possible to have Optimizely change all instances of a specific word on a page into an active hyperlink.

 

So let's say I have a 600 word article. I want every instance of the word "mp3 player" to change into a hyperlink.

 

Is this something that could be done?

JDahlinANF 09-18-15
 

Re: Find all instances of one word, and add a hyperlink. Code suggestions?

Are there any instances where the text "mp3 player" may exist on the page where you do *not* want to change it?  Can you narrow down where on the page that text may appear?

If you can narrow down where you are looking, (you said you have a 600 word article, so let's presume that this article uses <p> tags), you can replace the text in each <p>.

Here is an example of how to do this.  Run this in your console right now, on this page, and you will see every instance of "I want", in your original post, changed to a hyperlink with the word "Huzzah".

 

$.each($('p'), function(i,e) {
  $(e).html($(e).html().replace(/I want/g,'<a href="http://www.mp3player.com">Huzzah</a>'));
})

Re: Find all instances of one word, and add a hyperlink. Code suggestions?

You will need to use regular expressions to do something like this. Strings have a built-in .replace() method that you can leverage, and this method takes either a string as its first argument or a regular expression. In your case, you'd want to use a regular expression (i.e. regex). For example:

 

 

Some JavaScript in a text editor: http://screencast.com/t/C2rpb8nJTN

 

Here's the above code running in a browser dev tools console: http://screencast.com/t/MdywLHwV

 

Another example in the console with a totally different string: http://screencast.com/t/gGLPNK4snNU

 

 

In your case, it's a bit trickier, because you need to target all of the text on the page, and this could be in one or (more likely) MANY different HTML elements (i.e. "DOM elements"). You can get the text of a DOM element with jQuery easily, like:

 

MARKUP (i.e. HTML)

<div class="article">Some text here in a div HTML element</div>

 

JAVASCRIPT (i.e. jQuery)

$('.article').text(); //=> returns the text of the HTML element above

 

 

So you might have multiple paragraphs (i.e. <p> elements) or multiple divs or many other combinations of elements you'd need to check. But in the end, if you can target all of those elements with jQuery and then pull their text from the .text() method, then you can use the .replace()method with the regex like I demonstrated above to replace the text. Final example:

 

http://screencast.com/t/QAjHS3wNd

 

 

Here's a Codepen demonstrating this:

 

http://codepen.io/anon/pen/QjNRjr

-- Sean
UI Developer @ Blue Acorn

optimizely developer certification