2011-06-10 224 views

回答

5

一個選項:

>>> var str = "Lorem ipsum dolor sit amet consectetur adipiscing elit. Praesent mauris neque adipiscing nec malesuada id fermentum at eros. Curabitur eu neque nunc, et porta risus."; 
>>> str.replace(/([^,.]) /g, '$1, '); 
"Lorem, ipsum, dolor, sit, amet, consectetur, adipiscing, elit. Praesent, mauris, neque, adipiscing, nec, malesuada, id, fermentum, at, eros. Curabitur, eu, neque, nunc, et, porta, risus." 

或者,你可以走另一條路,以mimick negative lookbehind

>>> var str = "Lorem ipsum dolor sit amet consectetur adipiscing elit. Praesent mauris neque adipiscing nec malesuada id fermentum at eros. Curabitur eu neque nunc, et porta risus."; 
>>> str.replace(/([,.])? /g, function($0, $1) { return $1 ? $0 : ', '; }); 
"Lorem, ipsum, dolor, sit, amet, consectetur, adipiscing, elit. Praesent, mauris, neque, adipiscing, nec, malesuada, id, fermentum, at, eros. Curabitur, eu, neque, nunc, et, porta, risus." 
+0

難道這被重新用於在整個字符串中只插入3個(例如)? – ahabman 2011-06-10 13:33:57

+0

@ahabman嗯,我想你可以添加一個隨機元素:'str.replace(/([,。])?/ g,function($ 0,$ 1){return $ 1 || Math.random()> .2? $ 0:',';});'只會替換合格空格的〜1/5('.2')。如果你願意,你可以*記錄最大數量的空白(例如3)。 – jensgram 2011-06-14 05:32:49

1
@ jensgram的回答

紅寶石變化:

str.gsub(/([^,.]) /, $1 + ', ')