JavaScript JavaScript Basics (Retired) Storing and Tracking Information with Variables The Variable Challenge

Pro Student 689 Points

Adjusting the indefinite article ("A" or "An") based on the user-input word that follows

In 'The Variable Challenge,' I'm asked to construct a sentence using prompt() and display the sentence using document.write(). My sentence structure is

<indefinite article> <adjective> <noun> <verb>

and I want my script to adjust the indefinite article appropriately based on the adjective (i.e. if the adjective starts with a vowel, the indefinite article is 'An'). Can I make my code cleaner, and if so how?

Steven Parker
Steven Parker
202,109 Points

A live workspace URL is only temporary (this one has already expired). But you can create a persistent link using the "snapshot" function (the button with the camera icon).

1 Answer

Torben Korb
.a{fill-rule:evenodd;}techdegree seal-36
Torben Korb
Front End Web Development Techdegree Graduate 87,332 Points

This could be achieved if you for example "calculate" the article from the adjective input. You could do this with a combination of expressions inside an if statement and the String.prototype.startsWith method for example like

if (adjective.startsWith('a') || adjective.startsWith('e') ....and so on) {}

but this gets long and definitely a better and concise way would be a regular expression (RegEx) like this:

var adjective = prompt('Please type an adjective');
var article = 'a';
if (/^[aeiou]/gi.test(adjective)) article += 'n';
var sentence = 'There was once ' + article + ' ' + adjective;
var verb.....

Here in the if statement it tests the given user input for adjective against a RegEx pattern and if the string starts with any of the vowels in the squared brackets it adds an 'n' to the string in the article binding.

Also make sure which vowels you like to include because this differs from country to country, see Here is the Y also included in some cases and this would mean a lot more work to achieve something like this correctly.

Regular expressions are really powerful for tasks like this. Hope this helps you, Good coding!