Tom*_*mba 5 javascript arrays string
对于这个非常简单的问题抱歉,但我还是比较新的javascript.
我有一系列名字,比如说
var myArray = ['Hill M','Zhang F','Dong L', 'Wilkinson JS', 'Harris N'];
Run Code Online (Sandbox Code Playgroud)
我想返回一个字符串,其名称以逗号分隔,但在最后两个名称之间使用"和",即
'Hill M, Zhang F, Dong L, Wilkinson JS and Harris N'
Run Code Online (Sandbox Code Playgroud)
在javascript中执行此操作的最有效方法是什么?
如果我想转换名称和首字母,即返回,怎么样
'M Hill, F Zhang, L Dong, JS Wilkinson and N Harris'
Run Code Online (Sandbox Code Playgroud)
Ama*_*osh 19
Array :: slice()选择数组的一部分,并返回新数组.
Array :: join()将数组的所有元素连接成字符串
String :: concat()连接两个或多个字符串.
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
Run Code Online (Sandbox Code Playgroud)
要改变他们的顺序:
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
Run Code Online (Sandbox Code Playgroud)
万一你想知道 str.replace(/^(\S+)\s+(.+)$/, '$2 $1');
/^(\S+)\s+(.+)$/ 是一个匹配字符串的正则表达式:
^ #starts with
\S+ #one or more non whitespace characters, followed by
\s+ #one or more whitespace characters, followed by
.+ #one or more characters
Run Code Online (Sandbox Code Playgroud)
$1并且$2在替换字符串中表示来自正则表达式的第1组和第2组(括在括号中的子模式).
| 归档时间: |
|
| 查看次数: |
9062 次 |
| 最近记录: |