转换阵列逗号分隔文本 [英] Convert array to comma-delimited text
问题描述
此embarassingly简单的问题道歉,但我还是比较新的JavaScript。
我有名字的数组,像
myarray的无功= ['山M','张楼,董L','威尔金森JS,哈里斯N'];
我想返回一个字符串,用逗号分隔的名字,而是用和最后两个名字之间,即
山男,张楼,董L,威尔金森JS和哈里斯N'
什么是JavaScript来做到这一点的最有效方法是什么?
怎么样,如果我想转的姓名和缩写,即返回
'M山,女张某,L栋,JS威尔金森和N哈里斯
阵列::片()选择阵列的一部分,并返回新阵列。结果
阵列:: join()方法加入一个数组的所有元素转换为字符串结果
字符串:: CONCAT()连接两个或多个字符串。
myarray的无功= ['山M','张楼,董L','威尔金森JS,哈里斯N'];的console.log(myArray.slice(0,myArray.length - 1)。加入(,).concat(
和+ myarray的[myArray.length - 1]));//山男,张楼,董L,威尔金森JS和哈里斯ñ
要改变它们的顺序:
myarray的无功= ['山M','张楼,董L','威尔金森JS,哈里斯N'];对于(VAR I = 0; I< myArray.length;我++)
myArray的[I] = myArray的[I] .replace(/ ^(\\ S +)\\ S +(+)$ /,'$ 2 $ 1');的console.log(myArray.slice(0,myArray.length - 1)。加入(,).concat(
和+ myarray的[myArray.length - 1]));//中号山,女张某,L栋,JS威尔金森和N哈里斯
在如果你想知道关于 str.replace(/ ^(\\ S +)\\ S +(+)$ /,'$ 2 $ 1');
/ ^(\\ S +)\\ S +(+)$ /
是一个字符串匹配常规的前pression是:
^与#starts
\\ S + #one或多个非空格字符,然后是
\\ S + #one以上空格字符,然后是
+ #one或多个字符
$ 1
和 $ 2
替换字符串表示从第1和第2组(用括号括子模式)正则表达式。
Apologies for this embarassingly simple question but I'm still relatively new to javascript.
I have an array of names, something like
var myArray = ['Hill M','Zhang F','Dong L', 'Wilkinson JS', 'Harris N'];
I would like to return a string, with names separated by commas, but with "and" between the final two names, i.e.
'Hill M, Zhang F, Dong L, Wilkinson JS and Harris N'
What is the most efficient way to do this in javascript?
How about if I wanted to transpose the names and initials, i.e. to return
'M Hill, F Zhang, L Dong, JS Wilkinson and N Harris'
Array::slice() Selects a part of an array, and returns the new array.
Array::join() Joins all elements of an array into a string
String::concat() Concatenates two or more strings.
var myArray = ['Hill M','Zhang F','Dong L', 'Wilkinson JS', 'Harris N'];
console.log(myArray.slice(0, myArray.length - 1).join(', ').concat(
' and ' + myArray[myArray.length - 1]));
//Hill M, Zhang F, Dong L, Wilkinson JS and Harris N
To change their order:
var myArray = ['Hill M','Zhang F','Dong L', 'Wilkinson JS', 'Harris N'];
for(var i = 0; i < myArray.length; i++)
myArray[i] = myArray[i].replace(/^(\S+)\s+(.+)$/, '$2 $1');
console.log(myArray.slice(0, myArray.length - 1).join(', ').concat(
' and ' + myArray[myArray.length - 1]));
//M Hill, F Zhang, L Dong, JS Wilkinson and N Harris
In case you are wondering about str.replace(/^(\S+)\s+(.+)$/, '$2 $1');
/^(\S+)\s+(.+)$/
is regular expression that matches a string that:
^ #starts with
\S+ #one or more non whitespace characters, followed by
\s+ #one or more whitespace characters, followed by
.+ #one or more characters
$1
and $2
in the replacement string stands for 1st and 2nd groups (subpatterns enclosed in parentheses) from the regex.
这篇关于转换阵列逗号分隔文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!