Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do a "simple" find and replace in jQuery?

I am new to jquery, and I'm having trouble doing what I thought should be a very simple find and replace operation.

I want to change the text inside the the "<p>" tags. So for instance I might want to replace "your title" with "a 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 the jQuery which isn't doing anything:

$(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 cannot see what I'm doing wrong, any ideas?

Please help, thanks

like image 372
Ian G Avatar asked Dec 01 '22 08:12

Ian G


1 Answers

Any changes to strings in JS always produces a new string, rather than modifying what was there. Fortunately jQuery makes it easy to both retrieve 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:

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

  • Since replace() returns a new string each time, we can chain multiple calls together, so that we only need one .text() call and return statement.

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

like image 51
David Tang Avatar answered Dec 04 '22 03:12

David Tang