Darrell Darrell - 4 months ago 14
Javascript Question

Javascript pig latin regex not working

Trying to make a function that will convert English words into Pig Latin. The problem I have is when I check to see if the first letter is a vowel. I check using a regular expression:

if (str[0] === /[aeiou]/i)
but it doesn't work. Something is wrong with my regex but I look at references and it seems like that should work. I don't know what's going on. Can someone explain why the regex I am using does not work and what would be a similar working solution? If you run the code below, it doesn't give the right result, just saying beforehand.

function translate(str) {
var tag = "";
if (str[0] === /[aeiou]/i) {
tag = "way";
return str + tag;
}
else {
var count = 0;
for (var i = 0; i< str.length; i++) {
if (str[i] !== /[aeiou]/i)
tag += str[i];
else
break;
count = i;
}
console.log(count);
return str.slice(count + 1) + tag + "ay";
}
}


So when I run say
translate(overjoyed)
it should return "overjoyedway". And if I run
translate(glove)
it should return "oveglay".

Answer

What you have written is not the way you use regular expressions. The code if (str[0] === /[aeiou]/i) tests whether the first element of the str string array is both equal value and equal type as the regular expression: /[aeiou]/i. Characters are not the same type as regular expressions, so such a comparison will evaluate to false.

Think of the regular expression as a tool that can be used to search an entire string array for a match (all of str, not just str[0]). The web has a bunch of great examples, but to get you started, you might try using str.search(regexp) which will return the index of the first match (if found) or -1 (if no match).

Your code then becomes (without too much deviation from the original, and without trying to be clever or optimal):

function translate(str) {
    var tag = "";
    var pos = str.search(/[aeiou]/i); // This is ONE way to use regular expressions.
    if (pos == 0) { // First letter is a vowel.
        tag = "way";
        return str + tag;
    } else if (pos > 0) { // Some letter (not the first) is a vowel.
        // Instead of the loop checking each element, we already know where 
        // the match is found: at position = pos.
        console.log(pos); // Log the match position of the first vowel.
        tag = str.slice(0, pos); // The string before the first vowel.
        return str.slice(pos) + tag + "ay";
    }
}
Comments