2017-01-21 15 views
0

我試圖刪除它們,然後標點符號標點符號更換一個標點符號,我已經做到了,但我需要和或&隨機替換句子的最後一個,但第二個標點符號。如何使用和或隨機使用JavaScript

這裏是代碼

<html> 
    <head> 
     <script> 
      $(document).ready(function() { 
       for(var i=0;i<2;i++) 
      { 
       var remove_dot=document.getElementsByTagName("p")[i]; 
       var remove=remove_dot.innerHTML; 
       remove_dot.innerHTML = remove.replace(/[,|.-]+[\s]*([,|.-])/g, "$1"); 
       } 
       }); 
     </script> 
    <body> 
     <p>hello , . are you | . why , its ok , .</p> 
     <p>hey , . are you | . why | its ok , .</p> 
    </body> 

隨着上述腳本的幫助,我能夠去除標點符號後面標點符號 這裏是我的輸出

hello . are you . why , its ok . 
hey . are you . why | its ok . 

但是,當我需要更換倒數第二個標點隨機與和,&我怎麼能修改正則表達式 這是我的期望輸出。

 hello . are you . why and its ok . 
     hey . are you . why & its ok . 
+0

有超過標點符號 「| .-」。你想做他們全部,或只是那些? – RobG

回答

1
$(document).ready(function() { 
    $("p").each(function(){ 
     // get the text of this p 
     var text = $(this).text(); 

     // remove consecutive ponctuations 
     text = text.replace(/[,|.-]+\s*([,|.-])/g, "$1"); 

     // random "&" or "and" to replace the second from the last ponctuation 
     var rep = Math.random() < 0.5? "&": "and"; 

     // match the second from the last ponctuation 
     text = text.replace(/[,|.-]([^,|.-]*[,|.-][^,|.-]*)$/, rep + "$1"); 

     // reset the text of this p with the new text 
     $(this).text(text); 
    }) 
}); 

正則表達式匹配來自最後ponctuation第二是,尋找後跟什麼也沒後跟一個ponctuation,然後將文本$結束一個ponctuation一個ponctuation。所以唯一的匹配是最後一秒。

正則表達式還要檢查是否有最後ponctuation後一些文本(即不得包含ponctuation)。如果您確定在最後一個字典後面不會有文字,請使用此較短的正則表達式(/([,|.-])([^,|.-]*[,|.-])$/)。