2013-04-11 22 views
0

我有jQuery的驗證碼 - :不能匹配的正則表達式 - Jquery的

message = '#Usain Bolt #Usain Bolt #Usain Bolt'; message = " "+message+" "; 
var type1 = 'Usain Bolt';              
if(message.match(type1)) 
{ 
    var matchOne = new RegExp(' #'+type1+' ', 'g'); 
    var matchTwo = new RegExp('\n#'+type1+' ', 'g'); 

    message = message.replace(matchOne," @"+type1+" ").replace(matchTwo,"\[email protected]"+type1+" "); 
} 

得到的消息應該是@Usain Bolt @Usain Bolt @Usain Bolt

但它變成 - :@Usain Bolt #Usain Bolt @Usain Bolt

請告訴我問題。感謝您的幫助..

回答

1

問題是#Usain Bolt之間的空格是匹配的一部分。

" #Usain Bolt #Usain Bolt #Usain Bolt " 
^-----------^       first match 
         ^-----------^ second match 
      ^-----------^    no match (a character can only match once) 

使用單詞邊界,而不是:

message = '#Usain Bolt #Usain Bolt #Usain Bolt'; 
var type1 = 'Usain Bolt';              
if(message.match(type1)) 
{ 
    var matchOne = new RegExp('#\\b'+type1+'\\b', 'g'); 
    var matchTwo = new RegExp('\n#\\b'+type1+'\\b', 'g'); 

    message = message.replace(matchOne," @"+type1).replace(matchTwo,"\[email protected]"+type1); 
} 
+0

什麼出現R字邊界 – sanchitkhanna26 2013-04-11 07:19:29

+0

@RayZ:他們在匹配單詞字符之間的位置(包括字母,數字和下劃線:'\ w')和非單詞字符(或字符串的開始/結束)。 – 2013-04-11 07:24:04