Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialHiroshi N
1,946 PointsAdjusting 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?
1 Answer
Torben Korb
Front End Web Development Techdegree Graduate 91,433 PointsThis 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!
Steven Parker
231,275 PointsSteven Parker
231,275 PointsA 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).