2012-05-17 22 views
0
array = ['item1', 'item2', 'item3', 'item4'] 
output = array.toString() 

這讓我"item1,item2,item3,item4"但我需要空間,把它變成"item1, item2, item3, and item4"「和」我如何正則表達這個數組/字符串?

我怎麼能構建一個正則表達式的過程要做到這一點而不是substringing和查找/替換?

這是最好的方法嗎?

謝謝!

回答

1

該版本處理所有我能想到的變化:

function makeList (a) { 
    if (a.length < 2) 
    return a[0] || ''; 

    if (a.length === 2) 
    return a[0] + ' and ' + a[1]; 

    return a.slice (0, -1).join (', ') + ', and ' + a.slice (-1); 
}  

console.log ([makeList ([]), 
       makeList (['One']), 
       makeList (['One', 'Two']), 
       makeList(['One', 'Two', 'Three']), 
       makeList(['One', 'Two', 'Three', 'Four'])]); 

// Displays : ["", "One", "One and Two", "One, Two, and Three", "One, Two, Three, and Four"] 
0
var output = array.join(", "); 
output = outsput.substr(0, output.lastIndexOf(", ") + " and " + output.substr(output.lastIndexOf(" and ")); 
+0

哦,謝謝,然後「和「? – fancy

+0

啊,錯過了,編輯。 –

4

試試這個:

var array = ['item1', 'item2', 'item3', 'item4']; 
array.push('and ' + array.pop()); 
var output = array.join(', '); 
// output = 'item1, item2, item3, and item4' 

編輯:如果你真的想要一個基於正則表達式的解決方案:

var output = array.join(',') 
    .replace(/([^,]+),/g, '$1, ').replace(/, ([^,]+)$/, ' and $1'); 

另一個編輯:

這裏的另一個非正則表達式的方式,不能亂用原來array變量:

var output = array.slice(0,-1).concat('and ' + array.slice(-1)).join(', '); 
+0

+1,'array.pop()'位非常聰明。 –

+0

但它確實會改變可能導致下游問題的陣列。對於長度爲1的數組也不適用。 – HBP

+0

我猜如果這是個問題,你可以'array2 = array.slice()'; – jmar777

相關問題