1

I want to perform a "find and replace" operation on the text of certain elements stored in a jQuery object. I want to replace the text using the javascript function .replace(), which uses a regex selector. How to I correct this sample code?

$(JQUERY_OBJECT).html(
    $(this).text().replace(/REGEX_EXPRESSION/, 'REPLACEMENT_TEXT')
);

Note: The jQuery objects I am manipulating may contain child elements, but I do not want to preserve them. That is why I am using .text(). If it is possible to run the .replace() function without discarding inner elements, though, that would be great.

2 Answers 2

3

Provided you are using a very recent version of jQuery, the .html() method accepts a function as an argument, the function receives the current content as an argument and the return value is used to replace the current contents.

So the code would be:

$(JQUERY_OBJECT).html(function(idx,oldHtml){
   //idx is the index of the current element in the JQUERY_OBJECT
   return oldHtml.replace(/REGEX_EXPRESSION/, 'REPLACEMENT_TEXT')
});

http://api.jquery.com/html/#html2

Using .text() it's the same story

$(JQUERY_OBJECT).text(function(idx,oldText){
   //idx is the index of the current element in the JQUERY_OBJECT
   return oldText.replace(/REGEX_EXPRESSION/, 'REPLACEMENT_TEXT')
});

http://api.jquery.com/text/#text2

Or to re-write what you have already got using a combination of .html and .text

$(JQUERY_OBJECT).html(function(idx,oldHtml){
   return $(this).text().replace(/REGEX_EXPRESSION/, 'REPLACEMENT_TEXT')
});
Sign up to request clarification or add additional context in comments.

5 Comments

1. Could you provide a link to the jQuery docs explaining the input arguments you told me about. I could not find an explanation of what you told me on the jQuery .html() doc page.
2. I need to get the contents of the element using the .text() function, not .html(). Could you revise your answer accordingly?
2. But you would like to preserve the children of the elements, Don't think you can do that with .text()
1. The link is already in the answer, if you can't see it when the page is loaded, do a search in the browser for .html( function(index, oldhtml) ) when you get to that page.
Edited my answer to include the use of .text() in 2 different ways
0
var text = $(this).text().replace(/REGEX_EXPRESSION/, 'REPLACEMENT_TEXT');
$(this).text(text);

Or you could use replaceWith instead of the second text() if that's more appropriate?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.