學會正則表達式對開發者而言是個很是有用的技能,不少功能能夠簡單的用一句正則來實現。正則表達式
function DistinctString(s){ var a; while((a=s.replace(/(.)(.*?)\1/,"$1$2"))!=s) s=a; return s; }
function DistinctLines(s){ var a; while((a=s.replace(/(^.+(?:\r\n|\r|\n|$))((?:.*(?:\r\n|\r|\n))*?)^\1(?:\r\n|\r|\n|$)/m,"$1$2"))!=s) s=a; return s; }
還能夠利用此函數作基本數據類型去重:如字符數組,數值數組等數組
var a=[123,1234,9123,123,123,1234,321,123,9123,,1234]; DistinctLines(a.join("\n")).split("\n").filter(s=>s.length).map(s=>parseFloat(s));
//[123, 1234, 9123, 321]