jQuery find and replace with regex

I'll be the first to admit that this code snippet was not the ideal solution to my problem, but sometimes I take shortcuts. I know. It's terrible.

Anyway, I recently came across a bug in the Joomla EventList module that caused anchor urls to be output with &. The correct solution would have been to go into the module and fix it via php and some call to html entities or html special char. But I went the quick and dirty route by writing a jQuery find and replace snippet that uses a simple regex. Maybe the form of this will be helpful to someone who has better reasons for using it.

$("a").filter(function() { return $(this).attr('href').match(/&/); }).each(function(){ $(this).attr('href', $(this).attr('href').replace(/amp;/g,'') ); });

This looks the 'href' attribute on all anchors, checks for the presence of the & string, and replaces all occurrences with &.

Add new comment

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.