简体   繁体   中英

Javascript/jQuery Regular Expression code issue

I am working with jqDock on a DotNetNuke project. I ran jQuery.noConflict() and went through the jqDock.js file and changed all '$' to 'jQuery' (though I don't think it was necessary). In this little bit of code I have an issue:

altImage : function(){
      var alt = jQuery(this).attr('alt');
      return (alt && alt.match(/\.(gif|jpg|jpeg|png)$/i)) ? alt : false;

    } //end function altImage()

At the end of the regular expression there is a chunk that says $/i , My find/replace set this to jQuery. It broke the program. Is this because that '$' symbol isn't associated with jQuery there? Is it part of the Regular Expression? If so...what exactly is it saying?

The $ sign in this case is used as part of the regular expression, not as a call to jQuery, so that's why you had problems. It matches the end of the string that the regular expression is being performed on.

The $ matches the end of the string so it's not jQuery related here.

Some reading on regexp can be found here

Be really careful when doing such huge find/replaces in your code. You changed the $ sign used in a regular expression to a jQuery expression, which is wrong. Every replace of this magnitude (replace everything in a document by other string) should be done wisely.

Read noConflict documentation to see which options do you have when using it - there's even one that let's you still use $ for jQuery.

The usual style to writing jQuery plugins would mean that one would not need to replace $ throughout the plugin. Most plugins are written such that the plugin code is surrounde by a self-invoking anonymous function that passes in jQuery for a parameter $ such that $ refers to the jQuery object inside of that function. Like so

(function($) {

    // I can happily use $ here to refer to the jQuery object
    $.fn.myFunction ....

})(jQuery);

So be careful when doing a naive find/replace.

As others have already mentioned, in the context of a regular expression, $ is used to match the end of the string.

Finally, when using $.noConflict() , you can assign the jQuery object to a different alias and use that alias throughout the subsequent code. For example

var $j = $.noConflict();

// can use $j alias for jquery now
$j(document).ready(function($) { 
    // can use $j or $ for jQuery object inside this function as the 
    // jQuery object is passed in 
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM