2017-01-21 17 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)。如果您确定在最后一个字典后面不会有文字,请使用此较短的正则表达式(/([,|.-])([^,|.-]*[,|.-])$/)。