Can jQuery be used to find a string of text in HTML?

I am just starting to learn about jQuery and getting to know how jQuery allows me to use selectors to find specific identifiers and classes. But is it also possible to identify lines of plain old text inside a paragraph?

For example, let's say I wanted to find β€œgasoline” in these paragraph tags and convert it to a link:

<p>His veins burned gasoline. It kept his motor running but it never kept him clean.</p> 
+4
source share
3 answers

You would not use jQuery to replace. Instead, just use the javascript .replace() method.

(I gave the paragraph an identifier to indicate the correct paragraph.)

Try: 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 contents of the paragraph using jQuery .text()
  • Make .replace() in the text content, replacing the "gasoline" with the same text that was wrapped in the <a> element
  • Use the jQuery .html() method to update the paragraph with new content.

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

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

Park Avenue leads to ...

+4
source
 var text = jQuery("#someId").text(); text = textreplace(/(gasoline)/, "<a href='http://some.url.here'>$1</a>"); jQuery("#someId").html(text); 
+1
source
 $('p').text().replace('gasoline', '<a href="#">gasoline</a>'); 
+1
source

Source: https://habr.com/ru/post/1316716/


All Articles