By Using Replace And Regex: I Have Captured C, But I Want To Set It At The End Of Osonant Plus “ay” With Replace In Javascript
Here is he link: https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/pig-latin. By using replace and regex: I have capture
Solution 1:
See if that's what you want
function translatePigLatin(str) {
let regx = /(.*?)([^aeiou])(.*)/i
console.log(str.replace(regx, '$1$3ay$2'))
}
translatePigLatin("consonant")
// output onsonantayc
Your question is a bit vague, if not add more information in the comments
@Edited
Solution 2:
Pig Latin is a way of altering English Words. The rules are as follows:
If a word begins with a consonant, take the first consonant or consonant cluster, move it to the end of the word, and add "ay" to it.
If a word begins with a vowel, just add "way" at the end.
A possible solution:
function translatePigLatin(str) {
if (!/[aeiou]/.test(str)) { // if it does not contain vowels
return str + "ay";
} else if (/^[aeiou]/.test(str)) { // if it starts with a vowel
return str + "way";
} else { // if it starts with a consonant and has vowels
let regx = /(.*?)([aeiou])(.*)/i;
return str.replace(regx, "$2$3$1ay");
}
}
console.log(translatePigLatin("pig")); // igpay
console.log(translatePigLatin("rythm")); // rythmay
console.log(translatePigLatin("consonant")); // onsonantcay
The regular expression /(.*?)([aeiou])(.*)/i
means:
(.*?)
match as minimum characters as possible
([aeiou])
followed by a vowel and
(.*)
followed by the rest of the string.
By usinig the parenthesis, we are creating backreferences $1
, $2
, $3
that will store each of these values for later use with the replace method.
Post a Comment for "By Using Replace And Regex: I Have Captured C, But I Want To Set It At The End Of Osonant Plus “ay” With Replace In Javascript"