列出逗号和“和” - 分隔 [英] Make a list comma and "and"-separated

查看:411
本文介绍了列出逗号和“和” - 分隔的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 1 2 3您的字符串中包含分隔符(空格或其他字符) 
1 2
1

什么是最好/优雅在Javascript中的方式来格式化他们在以下方式?

 1,2和3
1和2
1

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

解决方案

 函数格式(输入,分隔符){
if(!input)return input;
input = input.split(separator ||'');
if(input.length === 1)return input [0];
return input.slice(0,-1).join(',')+'and'+ input.pop();





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

函数格式(输入,分隔符){
var save = input,pattern;

  
if(!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();

code


用法示例:

  format('1)))2(3)4))',')'); //1,2(3和4


You have strings with a separator character (a space or something else) like the following:

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

What is the best/elegant way in Javascript to format them in the following way?

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

Must works for any number of elements >= 1

解决方案

A basic solution :

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();
}

This one sticks to your own approach (trailing separator) :

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();
}

Usage example :

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

这篇关于列出逗号和“和” - 分隔的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆