views:

35

answers:

3

I'm just starting to learn about jQuery and am becoming familiar with how jQuery allows me to use selectors to search for particular IDs and classes. But is it also possible to identify strings of plain old text inside a paragraph?

For example, say I wanted to find "gasoline" within these paragraph tags and convert it into a link:

<p>His veins burned gasoline. 
   It kept his motor running but it never kept him clean.</p>
+1  A: 
var text = jQuery("#someId").text();
text = textreplace(/(gasoline)/, "<a href='http://some.url.here'&gt;$1&lt;/a&gt;");
jQuery("#someId").html(text);
Vivin Paliath
No need for the "p" in the selector; `jQuery('#someId')`
Matt
@Matt. True. Editing!
Vivin Paliath
+4  A: 

You wouldn't really use jQuery to do the replace. Instead just use javascript's .replace() method.

(I gave the paragraph an ID to specify the correct paragraph.)

Try it out: http://jsfiddle.net/yRCjN/1/

HTML

<p id='myparagraph'>His veins burned gasoline. 
   It kept his motor running but it never kept him clean.</p>

javascript/jQuery

     // Cache the selected element so it only runs once.
var $paragraph = $('#myparagraph');

     // Get the text and update it with the <a> tag
var newcontent = $paragraph.text().replace(/(gasoline)/,'<a href="/some/link/path">$1</a>');

     // Set the new content
$paragraph.html( newcontent );
  • You get the content of the paragraph using jQuery's .text()
  • Do a .replace() on the text content replacing "gasoline" with the same text wrapped in an <a> element
  • Use jQuery's .html() method to update the paragraph with the new content.

  • http://api.jquery.com/text/

  • http://api.jquery.com/html/

Park Avenue leads to...

patrick dw
Thanks very much! This should give me enough to work with. And thanks too for cluing me in to JSfiddle.
Paul Albert
+1  A: 
$('p').text().replace('gasoline', '<a href="#">gasoline</a>');
idrumgood