我怎样才能正则表达这个数组/字符串?

时间:2012-05-17 17:38:45

标签: javascript regex

array = ['item1', 'item2', 'item3', 'item4']
output = array.toString()

这会让我"item1,item2,item3,item4",但我需要将其转换为"item1, item2, item3, and item4"空格和“和”

我如何构建一个正则表达式进程来执行此操作而不是子串并查找/替换?

这是最好的方法吗?

谢谢!

3 个答案:

答案 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(', ');

答案 1 :(得分: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"]

答案 2 :(得分:0)

var output = array.join(", ");
output = outsput.substr(0, output.lastIndexOf(", ") + " and " + output.substr(output.lastIndexOf(" and "));