0

I have a list of product names that will need to be prepended with an indefinite article. My products look something like this:

  1. Book
  2. App
  3. eBook
  4. Record

These are stored in a DB and passed into a React app. I need to programmatically prepend each product with “a” or “an” accordingly, so they would appear like:

  1. A Book
  2. An App
  3. An eBook
  4. A Record

Is there a simple way to pull this off with JS alone?

Brandon Durham
  • 7,096
  • 13
  • 64
  • 101
  • Possible duplicate of [Javascript library to determine indefinite article](https://stackoverflow.com/questions/15366516/javascript-library-to-determine-indefinite-article) – Jack Wilsdon Dec 13 '18 at 04:26

2 Answers2

1

var nouns = [ "Book", "App", "eBook", "Record" ];
var vocals = "aeiouAEIOU";

for ( var n = 0; n < nouns.length; n++ )
{
     var first = nouns[n][0];
     if ( vocals.indexOf(first) >= 0 )
         nouns[n] = "An " + nouns[n];
     else
         nouns[n] = "A " + nouns[n];
}
console.log(nouns);

gives

 ["A Book", "An App", "An eBook", "A Record"]

on the console. Thanks to the simplicity of the English grammar. That won't work in any other language!

Axel Amthor
  • 10,980
  • 1
  • 25
  • 44
  • Sadly this breaks down in some cases, such as "user" (this snippet gives you "an user"). Take a look at [this answer](https://stackoverflow.com/a/15366802/2664985) for a more complete (and more complex) solution. – Jack Wilsdon Dec 13 '18 at 04:25
1

You can use this simple code that checks the first letter of the given word and use the correct article:

function prependArticle(word){
  var vowels = 'aeiou';
  var firstLetter = word[0].toLowerCase();
  if(vowels.indexOf(firstLetter) > -1)
    return 'An ' + word;
  else
    return 'A ' + word;
}

//Test the function:
document.write(prependArticle('Book') + '<br/>');
document.write(prependArticle('App') + '<br/>');
document.write(prependArticle('eBook') + '<br/>');
document.write(prependArticle('Record') + '<br/>');

However, that's not perfect. For instance the word "Unicorn" starts with "U", yet it should prepended with "A", not "An". Similarly, the word "Hour" start with "H" yet, it should be prepended with "An", not "A". Also acronyms have some complexity because we prepend them based on how we pronounce them, not how we write them.

Racil Hilan
  • 24,690
  • 13
  • 50
  • 55
  • Thanks so much! I accepted the other answer since they're both so similar and his came first. I upvoted yours, too. I was thinking the same thing… hard to make this bulletproof. Fortunately it's for a limited set of products, so I can build in some sort of acception list that trumps the conditional. – Brandon Durham Nov 22 '15 at 16:53