array = ['item1', 'item2', 'item3', 'item4']
output = array.toString()
這讓我"item1,item2,item3,item4"
但我需要空間,把它變成"item1, item2, item3, and item4"
「和」我如何正則表達這個數組/字符串?
我怎麼能構建一個正則表達式的過程要做到這一點而不是substringing和查找/替換?
這是最好的方法嗎?
謝謝!
array = ['item1', 'item2', 'item3', 'item4']
output = array.toString()
這讓我"item1,item2,item3,item4"
但我需要空間,把它變成"item1, item2, item3, and item4"
「和」我如何正則表達這個數組/字符串?
我怎麼能構建一個正則表達式的過程要做到這一點而不是substringing和查找/替換?
這是最好的方法嗎?
謝謝!
該版本處理所有我能想到的變化:
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"]
var output = array.join(", ");
output = outsput.substr(0, output.lastIndexOf(", ") + " and " + output.substr(output.lastIndexOf(" and "));
試試這個:
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(', ');
哦,謝謝,然後「和「? – fancy
啊,錯過了,編輯。 –