Hi! I'm currently reworking my site, so although this content is still online things may change or look odd. Please get in touch to find out how I can help you!

Simple Text Replacement in jQuery

This morning, my friend-across-the-water Candi was having an issue with JavaScript’s replace() function - after a bit of head-scratching I realised that it just doesn’t work the way you expect it to if you’re used to using a framework like jQuery.

To explain what I mean, consider the following code. You might expect that it will replace all instances of “foo” with “bar” in the content of $('#baz')

$('#baz').html().replace('foo', 'bar');

…but you’d be wrong. It actually has no effect on $('#baz') at all. This is because replace() doesn’t actually modify the content it’s passed, but returns the modified string. So the correct code would be:

$('#baz').html($('#baz').html().replace('foo', 'bar'));

Not particularly intuitive, and not very elegant either. So it set me thinking that there must be a more “jQuery-style” way to do this, and I came up with the following two functions:

$.fn.textReplace = function(target, replacement) {
	this.html(this.html().replace(target, replacement));
	return this;
}

$.fn.attrReplace = function(attr, target, replacement) {
	this.attr(attr, (this.attr(attr).replace(target, replacement)));
	return this;
}

How Do They Work?

The two functions perform similar but slightly different tasks. textReplace() will modify the HTML content of an element, so you can pass it pretty much anything, be it a <p>, <textarea> or even your <body> and it will do its thing - but it’s best to be as specific as you can to avoid lots of processing.

attrReplace() will only perform a text replacement on the specified attribute of the element you call it on. So, if you want to change an <img>’s src, or an <input>’s value, attrReplace() is your friend.

Both functions pipe their target and replacement parameters straight into the standard replace() function, so you can pass regular expressions if you like.

Finally, these functions work in the intuitive jQuery style you know and love - they even return this so you can carry on chaining methods to your heart’s content.

Check out the demo for some examples of textReplace() and attrReplace() in action.

Tags: JavaScript jQuery

Feedback

Sorry, feedback is now closed on this post, but please feel free to get in touch if you would like to talk about it!

Or find posts by tag →

Friends & Influences

  1. Aching Brain
  2. Andy Budd
  3. Anthony Killeen
  4. Ben Everard
  5. Cameron Moll
  6. Dan Cederholm
  7. Dan Mall
  8. Dave Shea
  9. Elliot Jay Stocks
  10. Jamie Knight
  11. Jamie Rumbelow
  12. Jason Santa Maria
  13. Jeff Croft
  14. Jeffrey Zeldman
  15. Jeremy Keith
  16. Jon Hicks
  17. Khoi Vinh
  18. Mark Boulton
  19. Matt Croucher
  20. Nocturnal Monkey
  21. Sarah Parmenter
  22. Shaun Inman
  23. Simon Collison
  24. Tim Van Damme
  25. Toby Howarth