通过使用替换和正则表达式:我已经捕获了 c,但我想将它设置在 osonant 的末尾加上“ay",并在 Javascript 中替换 [英] 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
问题描述
通过使用替换和正则表达式:我已经捕获了 c
,但我想在 onsonant
的末尾加上 ay
使用JavaScript 中的 replace
函数
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
这是我的代码:
function translatePigLatin(str) {
let regEx=/([bcd-fgh-klmn-pqrst-vwxyz])/i
console.log(str.replace(regEx, '$1,'))
}
translatePigLatin("consonant");
推荐答案
Pig Latin 是一种改变英文单词的方式.规则如下如下:
Pig Latin is a way of altering English Words. The rules are as follows:
如果一个词以辅音开头,取第一个辅音或辅音簇,将其移到词尾,并添加ay".
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.
如果单词以元音开头,只需在末尾添加way"即可.
If a word begins with a vowel, just add "way" at the end.
一个可能的解决方案:
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
正则表达式/(.*?)([aeiou])(.*)/i
表示:
(.*?)
匹配尽可能少的字符
([aeiou])
后跟元音和
(.*)
后跟字符串的其余部分.
(.*)
followed by the rest of the string.
通过使用括号,我们正在创建反向引用 $1
、$2
、$3
,它们将存储这些值中的每一个供以后使用replace 方法.
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.
这篇关于通过使用替换和正则表达式:我已经捕获了 c,但我想将它设置在 osonant 的末尾加上“ay",并在 Javascript 中替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!