开发者

Convert array to comma-delimited text

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开发者_Go百科 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.


Use join for combining the values in the array.

var myJoinedString = myArray.join(',');


var myArray = ['Hill M','Zhang F','Dong L', 'Wilkinson JS', 'Harris N'];
var replaced = myArray.map(function(elem) {
  return elem.replace(/(\S+)\s+(\S+)/, "$2 $1");
});
var last = replaced.pop()
var result = replaced.join(", ") + " and " + last;

alert(result)


Try this:

if (myArray.length <= 1) {
    str = myArray.join();
} else {
    str = myArray.slice(0, -1).join(", ") + " and " + myArray[myArray.length-1];
}

And for your swapping part:

myArray.map(function(val) { return val.split(" ").reverse().join(" "); })
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜