-3

I'm trying to use regex to evaluate whether the newArray at index 0 is equivalent to the value stored in vowel. I know that this method doesn't work but I don't understand why. BTW I've just started learning how to code so I only really know Vanilla JS

function translate(val) {
    let newArray = Array.from(val)
    let vowel = /^[aeiouy]/gi
    let consonant = /[^aeiouy]/
    if (newArray[0] == vowel) {
        return 'vowel';
    } else if (newArray[0] == consonant) {
        return 'consonant'
    } {
        return 'none';
    }
}
 translate('inglewood')
Wiktor Stribiżew
  • 561,645
  • 34
  • 376
  • 476
soreti
  • 11
  • 5

2 Answers2

1

You should be using the regex test method here:

function translate(val) {
    let vowel = /^[aeiouy]/gi;
    let consonant = /^[^aeiouy]/;
    if (vowel.test(val)) {
        return 'vowel';
    } else if (consonant.test(val)) {
        return 'consonant'
    } else {
        return 'none';
    }
}

console.log(translate('inglewood'));

Note: I don't see any point in using Array.from() here. Instead, we can just run test directly against an input string.

Tim Biegeleisen
  • 451,927
  • 24
  • 239
  • 318
0

You need to .test() the string with the regex

function translate(val) {
    let newArray = Array.from(val)
    let vowel = /^[aeiouy]/gi
    let consonant = /[^aeiouy]/

    if ( vowel.test( newArray[0] ) ) {
        return 'vowel';
    } else if ( consonant.test( newArray[0] ) ) {
        return 'consonant'
    } {
        return 'none';
    }
}
console.log( translate('inglewood') );
Thum Choon Tat
  • 2,866
  • 1
  • 20
  • 22