Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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

Hiroshi N
Hiroshi N
1,946 Points

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

https://teamtreehouse.com/workspaces/40993330#

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
210,487 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
seal-mask
PLUS
.a{fill-rule:evenodd;}techdegree seal-36
Torben Korb
Front End Web Development Techdegree Graduate 88,520 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 https://simple.wikipedia.org/wiki/Vowel. 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!