2

I am trying to create a string with where i want to have the following

  1. there should be and word before the last word in the sentence
  2. if there is just one word then no and.

for and array ['john','harry', 'darren']

i expect below

e.g john harry and daren

is it even a valid case for internationalisation or am i better off just programming do this?

hafiz ali
  • 1,378
  • 1
  • 13
  • 33
  • 3
    its a style choice, not internationalization, so you should just code it. Depending on context the final word could be 'or' or nothing, and then there's the [Oxford comma](https://en.wikipedia.org/wiki/Serial_comma) – pilchard Mar 01 '22 at 10:58
  • 1
    I18n would be relevant if you wanted to do this in a localised fashion, e.g. "johnとharryとdarren" in Japanese… – deceze Mar 01 '22 at 11:03

2 Answers2

0

You may create a function, and the body will look something like this:


function myFunc (a) {
    if (a.length > 1) {
        const exceptLast = a.slice(0, -1)
        let last = a.slice(-1)
        last = ['and', ...last]
        return [...exceptLast, ...last].join(" ")
    }
    return a[0]
}

Test it like this:


const da = ['b', 'cc', 'ddd']
const da1 = ['b']
const da2 = ['b']



console.log(myFunc(da))
console.log(myFunc(da1))
console.log(myFunc(da2))
Maifee Ul Asad
  • 3,992
  • 6
  • 38
  • 86
0

What you are looking for is Intl.ListFormat:

const names = ['john','harry', 'darren'];

const formatter = new Intl.ListFormat('en', { style: 'long', type: 'conjunction' });

console.log(formatter.format(names)); // prints john, harry, and darren

If you want to use the default locale, replace 'en' with undefined.

Gyum Fox
  • 3,287
  • 2
  • 41
  • 71