2013-08-21 157 views
0

我有以下文字:在正则表达式替换@符号

Title %%% [email protected]

我有以下脚本:

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(/%%%[^@]*/," ")); 

的captionUnderlay上面会显示@mydomain.com

我可以使用下面的kludge来解决问题,但我想知道问题是什么(我接管别人编写的代码)。

如果我从正则表达式中删除[^@],它会显示所有内容。如果我用[^@]代替[^}],它会正常工作,除非我在文本中有}

如何防止发生这种情况?

+2

'“标题%%% [email protected]” .replace(/%%%.*/,'')'---为什么它不是预期的结果? ('Title'后跟2个空格,不会停在'@'上) – zerkms

+1

是否有换行符? '\ n'或'\ r'。 –

+0

zerkms:我希望标题显示,但标题@ mydomain.com显示。 – user2654985

回答

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

正在查找%%%后跟0个或多个字符,它们不是@。给定字符串"Title %%% [email protected]"--这意味着它找到%%% info(因为信息后有@符号),然后用空格替换(," ")。制作字符串"Title @mydomain.com"

的代码顶部的表达实际上是正确的,如果你只是想"Title "

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

由于这后3百分号发现任何字符(.)0次或更多次。但这不过留下空间Title后 - 纠正这一点,我们将使用下面的表达式全内饰回报:

固定表达

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