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.
Use join for combining the values in the array.
var myJoinedString = myArray.join(',');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With