I'm trying to create a higher order function that would do two things.
First: it would check the first letter of a string if it's a vowel, if it is, it would append at the end of the string 'way'.
I've done so with this code:
const vowel = /[aeiou]/;
const consonant = /^[^aeiou]/gi;
const chaVow = 'way';
const chaCon = 'ay';
function pigLatinVowel(str) {
if (!str.charAt(0) == vowel) {
return str
} else {
return str.concat(chaVow)
}
}
console.log(pigLatinVowel("algorithm"));
Then I need to code to run a specific task while checking for consonants instead. It has to check if the first letter (or group of letters) of a string is a consonant, push it to the end of the string and append the string 'ay'. I'm having problems with the regex, its not exactly what I'm looking for but I'm utterly lost. Here goes the code I'm using so far:
const vowel = /[aeiou]/;
const consonant = /^[^aeiou]/gi;
const chaVow = 'way';
const chaCon = 'ay';
function pigLatinConsonant(str) {
str = str.split('');
let filtered = str.filter(a => a.match(consonant));
return filtered;
}
console.log(pigLatinConsonant("glove"));
Ideally the regex would stop at the first vowel so it doesn't give me this output: [ 'g', 'l', 'v' ]
Obviously the function is not done yet and there is still some work to do. I don't want the whole answer as how would I go about creating the HoF and the rest, I'm learning through a course @FreeCodeCamp and I'm stubborn about it but I'm failing miserably at this step :(.
Perhaps I'm failing somewhere else but so far this function is driving me crazy.
Help much appreciated!
CodePudding user response:
Use a regular expression that matches a sequence of consonants at the beginning of a string:
function startingConsonants(string) {
let m = string.match(/^[^aeiou] /);
return m && m[0];
}
CodePudding user response:
You can use a regex with a capturing group to get all the consonants before the first vowel in the string /^([^aeiou] )[aeiou]/i
. Then base your logic on the result of match()
const atternpay = /^([^aeiou] )[aeiou]/i;
const chaVow = 'way';
const chaCon = 'ay';
function pigLatinConsonant(str) {
let con_prefix = str.match(atternpay);
if (null === con_prefix)
return str chaVow;
return str.substring(con_prefix[1].length) con_prefix[1] chaCon
}
console.log(pigLatinConsonant("glove"));
console.log(pigLatinConsonant("also"));