简体   繁体   中英

Replacing @ symbols in regular expressions

I have the following text:

Title %%% info@mydomain.com

I have the following script:

update: function(){
    this.AjaxImage(this.mainImage.current);
    // /[$-/:-?{-~!"^_`\[\]]/ Updated 05.22.10, changed .replace(/%%%[^%]*/,' ') to .replace(/%%%.*/,' ') because an escaped space (%20) was causing markup to appear on the page. DE 
    // only show the title and year below the image, %%% is the delimiter
    var caption = this.detailBin[this.mainImage.current]
                      .innerHTML.replace(/%%%.*/,' '); 
    this.overlayCaption('hide');
    this.controls.counter.update(this.mainImage.current+1);
    this.utilities.updateHash(this.mainImage.current+1);
    this.captionUnderlay.update(caption);

    // show everything under "more info"
    this.captionText = this.detailBin[this.mainImage.current]
                           .innerHTML.replace('%%%',' '); 
    this.hasMoreInfo = (this.captionText.length > caption.length+9) ? true : false;
    if(!this.hasMoreInfo) 
        this.controls.captionToggle.hide();
    else 
        this.controls.captionToggle.show();
}

this.captionUnderlay.update(this.detailBin[this.currentImage]
                                .innerHTML.replace(/%%%[^@]*/," "));

The captionUnderlay above will show @mydomain.com .

I can solve the problem using the kludge below, but I want to understand what the problem is (I'm taking over the code that was written by someone else).

If I remove [^@] from the regular expression, it shows everything. If I substitute [^@] for [^}] it works fine unless I have a } in the text.

How do I prevent this from occurring?

.replace(/%%%[^@]*/," ")

Is looking for %%% followed by 0 or more characters that are not a @ . Given the string "Title %%% info@mydomain.com" - that means it finds %%% info (as there is an @ symbol after info), which is then replaced by a space ( ," " ). Making the string "Title @mydomain.com" .

The expression at the top of the code is actually correct if you only want "Title "

.replace(/%%%.*/,' ')

As this finds any character ( . ) 0 or more times after 3 percent signs. This does however leave the space after Title - to correct this we would use the expression below for a fully trimmed return:

Fixed expression

.replace(/\s*%%%.*/,'')

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