问题
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 captured c
, but I want to set it at the end of onsonant
plus ay
using the replace
function in JavaScript
Here is my code:
function translatePigLatin(str) {
let regEx=/([bcd-fgh-klmn-pqrst-vwxyz])/i
console.log(str.replace(regEx, '$1,'))
}
translatePigLatin("consonant");
回答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
回答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.
来源:https://stackoverflow.com/questions/61448161/by-using-replace-and-regex-i-have-captured-c-but-i-want-to-set-it-at-the-end-o