jQuery regex replace syntax
|
View:
New views
4 Messages
—
Rating Filter:
Alert me
|
|
|
jQuery regex replace syntaxHello. Does jQuery have a nice way to do a regular expression replace on an attribute? I currently have this: $j(this).attr( 'src' , $j(this).attr('src').replace( /regex/ , 'text' ) ) But that's messy, I'd prefer this: $j(this).replaceAttr( 'src' , /regex/ , 'text' ) Is something like that possible? Thanks, Peter |
|
|
Re: jQuery regex replace syntaxOn Mar 14, 10:27 pm, Peter Boughton <bought...@...> wrote: > Hello. > > Does jQuery have a nice way to do a regular expression replace on an > attribute? > > I currently have this: > > $j(this).attr( 'src' , $j(this).attr('src').replace( /regex/ , > 'text' ) ) > > But that's messy, I'd prefer this: > > $j(this).replaceAttr( 'src' , /regex/ , 'text' ) > > Is something like that possible? This is possible: $j(this).attr('src', function() { return this.src.replace(/regex/,'text'); }); --Klaus |
|
|
Re: jQuery regex replace syntaxThanks Klaus. I solved this by writing a simple plugin/extension to allow the nicer syntax... jQuery.fn.replaceAttr = function(aName,rxString,repString) { return this.each ( function() { jQuery(this).attr ( aName , jQuery(this).attr(aName).replace(rxString,repString) ) } ); } So now I've just got that included and I can do the nice simple three argument function. :) On Mar 15, 1:33 am, Klaus Hartl <klaus.ha...@...> wrote: > On Mar 14, 10:27 pm, Peter Boughton <bought...@...> wrote: > > > Hello. > > > Does jQuery have a nice way to do a regular expression replace on an > > attribute? > > > I currently have this: > > > $j(this).attr( 'src' , $j(this).attr('src').replace( /regex/ , > > 'text' ) ) > > > But that's messy, I'd prefer this: > > > $j(this).replaceAttr( 'src' , /regex/ , 'text' ) > > > Is something like that possible? > > This is possible: > > $j(this).attr('src', function() { > return this.src.replace(/regex/,'text'); > > }); > > --Klaus |
|
|
Re: jQuery regex replace syntaxOn Mar 15, 1:15 pm, Peter Boughton <bought...@...> wrote: > Thanks Klaus. > > I solved this by writing a simple plugin/extension to allow the nicer > syntax... > > jQuery.fn.replaceAttr = function(aName,rxString,repString) > { > return this.each > ( function() > { > jQuery(this).attr > ( aName > , jQuery(this).attr(aName).replace(rxString,repString) > ) > } > ); > > } > > So now I've just got that included and I can do the nice simple three > argument function. :) That's the good thing about jQuery, easily extensible. Nice. I see some room for optimization by the way, you don't need the each - attr already returns the jQuery object - which saves you from creating two new jQuery objects in the loop. jQuery.fn.replaceAttr = function(aName, rxString, repString) { return this.attr( aName, function() { return jQuery(this).attr(aName).replace(rxString, repString); } ); }; --Klaus |
| Free embeddable forum powered by Nabble | Forum Help |