javascriptreactjsintl

Can i use internationalisation api to format sentence to have "and" word before last item?


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?


Solution

  • 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.