制作一个列表逗号和“和” - 分隔

时间:2013-12-07 07:21:53

标签: javascript string formatting

您的字符串包含分隔符(空格或其他内容),如下所示:

"1 2 3"
"1 2"
"1"

Javascript中以下列方式格式化它们的最佳/优雅方式是什么?

"1, 2 and 3"
"1 and 2"
"1"

必须适用于任意数量的元素> = 1

5 个答案:

答案 0 :(得分:2)

基本解决方案:

function format(input, separator) {
    if (!input) return input;
    input = input.split(separator || ' ');
    if (input.length === 1) return input[0];
    return input.slice(0, -1).join(', ') + ' and ' + input.pop();
}

这个坚持你自己的方法(尾随分隔符):

function format(input, separator) {
    var save = input, pattern;
    if (!input) return input;
    pattern = '[^\\' + (separator || ' ') + ']+';
    input = input.match(new RegExp(pattern, 'g'));
    if (!input) return save;
    if (input.length === 1) return input[0];
    return input.slice(0, -1).join(', ') + ' and ' + input.pop();
}

用法示例:

format('1)))2(3)4))', ')'); // "1, 2(3 and 4"

答案 1 :(得分:1)

几年前在StackOverflow上找到了这个。这是一个非常基本的实现 - 为方法添加分隔符参数并不困难。

    function formatList(myString){
        if ( myString.indexOf(" ") === -1 ) return myString;

        if ( myString.indexOf(" ") === myString.lastIndexOf(" ") ){
            return myString.replace(" ", " and ");
        } 

        var former = myString.substr(0, myString.lastIndexOf(" "));
            former = former.replace(/ /g,", ");

        var latter = myString.substr(myString.lastIndexOf(" "), myString.length -1);
        var output = former + " and " + latter;

        return output; 
    }

formatList("1"); // 1
formatList("1 2"); // 1 and 2
formatList("1 2 3"); // 1, 2 and 3
formatList("1 2 3 4"); // 1, 2, 3 and 4

答案 2 :(得分:0)

如果你也有一个数组,这个可以工作。它使用Query $ .inArray,如果不使用jQuery并仅以数组形式或字符串形式输入,则可以省略它。

  // Transform a string made of substrings separated by a separator (default "#")
  // or an array in a string that is comma (", ") separated and that has an "and" 
  // separaing the last element. 
  // Ex: 
  //     toCommaAnd("1#2#3")     -> "1, 2 and 3"
  //     toCommaAnd("1 2 3"," ") -> "1, 2 and 3"
  //     toCommaAnd("Mr. Cinelli#Ms. Cinelli") ->"Mr. Cinelli and Ms. Cinelli"
  //     toCommaAnd(["a", "b"])  -> "a and b"
  //
  // !!  toCommaAnd("1#2#3#")    ->   become "1, 2 and 3" TOO so you can 
  //                                  concatenate  elements in loops without 
  //                                  caring about special case for first or
  //                                  last element.  


  function toCommaAnd(str, separator) {
      var ar = $.isArray(str) ? str : str.split(separator || "#"),  
          commaUntil = ar.length - 1,
          ret = ar[0], 
          i;

      //This is just for the 1#2#3# cases.
      if (commaUntil > 0 && ar[commaUntil] === ""){
          commaUntil--;
      }

      for (i = 1; i < commaUntil; i++){
          ret += ", " + ar[i];
      }
      if (commaUntil > 0)
          ret += " and " + ar[commaUntil];

      return ret ;
  },  

答案 3 :(得分:0)

您可以使用:

<!DOCTYPE html>
<html>
<body>
<script>
cars=["Elem 1","Elem 2","Elem 3","Elem 4"];
var s = '';
var sep = '';
for (var i=0;i<cars.length;i++)
{
  if(i==cars.length-1){
    s=s+" and "+cars[i];
  }else{
   s=s+sep+cars[i];
   sep = ', ';
  }
}
document.write(s + "<br>");
</script>
</body>
</html>

答案 4 :(得分:0)

这个非常扭曲:

function format(input, separator) {
    var idx = input.indexOf(separator || ' ');
    if (idx === -1) return input;
    return input.substring(0, idx++) + (
        input.indexOf(separator || ' ', idx) === -1 ? ' and ' : ', '
    ) + (
        format(input.slice(idx), separator)
    );
}

但无法处理连续和尾随分隔符:

format('1|2||3|', '|'); // "1, 2, , 3 and "