1

I'm trying to write a simple Pig Latin code. I want to check if the first letter of the input string is a vowel, if so then to run that certain code. How can I ask if y is equal to one of those values.

function pigLatin() {
    var y = prompt("Enter a word:")
    if (y.charAt(0) = a,e,i,o,u) {
        var pigLatin = y + "ay";
        document.getElementById("answer").innerHTML = "Answer is: " + pigLatin;
    } else {
        var wordLength = y.length + 1;
        var pigLatin = y.substring(1, wordLength) + y.charAt(0) + "ay";
        document.getElementById("answer").innerHTML = "Answer is: " + pigLatin;
    }
}
3
  • 2
    = assigns, == or === checks for equality (apart from the invalid syntax a,e,i,o,u) Commented Sep 12, 2017 at 8:53
  • Please see Equality comparisons Commented Sep 12, 2017 at 8:55
  • Possible duplicate of several SO posts in relation to equality of which one is stackoverflow.com/questions/359494/… Commented Sep 12, 2017 at 8:56

2 Answers 2

8
if (y.charAt(0) = a,e,i,o,u) {

...is not valid.

Try...

if ('aeiou'.includes(y.charAt(0))) {

Your problems are...

  • Strings must be quoted, even if they're only one character long.
  • An array must be wrapped with [ and ] (unless constructed via another means such as with the Array constructor)
  • You can't use the assignment operator (=), nor any equivalency operator (== or ===) to automatically check for the presence of an item in an array. Since you're checking against a list of single characters, you can directly use String.prototype.includes() on it.

If the user cancels the prompt(), you will get null also, which you are not handling (it will crash on the condition mentioned).

Sign up to request clarification or add additional context in comments.

4 Comments

Or perhaps if ('aeiou'.includes(y.charAt(0))) {.
@Rajesh That regular expression is wrong. Maybe you meant /[aeiou]/? (I'd argue this is a bad use case for a regular expression anyway.)
@Rajesh While it could work, I don't see the need to use a regex over normal string methods
This is the first time asking a question on here. You guys are amazing people <3
0

First, you need the letters to be in quotes in this

if (y.charAt(0) = a,e,i,o,u)

Second, use === for equals.

Third you want it to be one of the vowels 'a', 'e', 'i', 'o', 'u'.

You could compare the indexOf the char against -1:

if (['a', 'e', 'i', 'o', 'u'].indexOf(y.charAt(0)) !== -1)
//...

2 Comments

in doesn't work like that. It checks for keys in an object, here you have an array of chars.
Of course; that gets an index.. the other answer is better anyway.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.