How to make "simple" search and replace in jQuery?

I am new to jquery and am having problems with what, in my opinion, should be a very simple search and replace operation.

I want to change the text inside the "<p>" tags. So, for example, I could replace "your title" with "title".

<div id="ValidationSummary"> <ul> <li> <p> Please specify your title</p> </li> <li> <p> Please enter your first name</p> </li> <li> <p> Please enter your surname</p> </li> </ul> </div> 

and here is jQuery that does nothing:

 $(function() { $('#ValidationSummary').text().replace("your title", "a title"); $('#ValidationSummary').text().replace("first name", "christian name"); $('#ValidationSummary').text().replace("your surname", "your last name"); }; 

I really don’t see what I'm doing wrong, any ideas?

Please help thanks

+4
source share
4 answers

Any changes to strings in JS always cause a new line , not change what was there. Fortunately, jQuery makes it easy to extract and modify text at the same time:

 $('#ValidationSummary p').text(function (i, old) { return old .replace('your title', 'a title') .replace('first name', 'christian name') .replace('your surname', 'your last name'); }); 

Explanation:

  • return string from .text() tells jQuery to replace what was there (passed as old ) with this new string.

  • Since replace() returns a new line each time, we can bind several calls together, so we only need one call to .text() and return .

  • I used the '#ValidationSummary p' selector since using .text() or .html() will replace the entire contents of the element it is working on.

+14
source
 $(function() { var text = $('#ValidationSummary').text().replace("title", "your title"); // this will give the text after replacement, but it will not set the text to ValidationSummary $('#ValidationSummary').text(text); text = $('#ValidationSummary').text().replace("first name", "christian name"); $('#ValidationSummary').text(text); text = $('#ValidationSummary').text().replace("your postcode", "your zipcode"); $('#ValidationSummary').text(text); }; 
+4
source

In JSFIDDLE .

 $(function() { $('#ValidationSummary').html($('#ValidationSummary').html().replace("title", "Mister")); $('#ValidationSummary').html($('#ValidationSummary').html().replace("first name", "ABC")); $('#ValidationSummary').html($('#ValidationSummary').html().replace("surname", "XYZ")); }); 

It works, but I do not consider it reliable.

+1
source

TRY IT...

  $('#ValidationSummary').text($('#ValidationSummary').find('P').text().replace("title", "your title")); $('#ValidationSummary').text($('#ValidationSummary').find('P').text().replace("first name", "christian name")); $('#ValidationSummary').text($('#ValidationSummary').find('P').text().replace("your postcode", "your zipcode")); 
0
source

All Articles