简体   繁体   中英

Array to string and replace last comma in the array (not string)

I have an array (please note that tropical and pineapple are in the same array value):

'apple', 'pear', 'orange', 'tropical, pineapple'

I wish to turn it into a string and replace the the last comma with an 'and'.

I perform:

fruits.join(', ');
fruits.replace(/,([^,]*)$/,'\ and$1');

This gives:

apple, pear, orange, tropical and pineapple

Whereas I require the last comma from the array to be replaced and not any comma in the array's values.

I'm looking for:

apple, pear, orange and tropical, pineapple

Is this possible?

Just don't join on the complete array. Instead, use

fruits.slice(0, -1).join(", ")+" and "+fruits[fruits.length-1];

If you don't need the array any more, you can also mutate it, which makes things a little easier:

var last = fruits.pop();
console.log(fruits.join(", ")+" and "+last);

Also we need to take into account the case of an empty input, so it should rather look like

if (fruits.length <= 1)
    return fruits.join(", ");
else
    return fruits.slice(0, -1).join(", ")+" and "+fruits[fruits.length-1];

which you might want to wrap in a helper function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM