编写一个函数translate(),将文本翻译成“rövarspråket”。也就是说,每个辅音都加倍,并在它们之间出现“o”。例如,翻译(“这很有趣”)应该返回字符串“tothohisos isos fofunon”
答案 0 :(得分:1)
简单的正则表达式替换 - 但您需要自己决定是否要将Y
视为元音或辅音:
function translate(text, cons, char) {
// translate text into "rövarspråket"
// text - string
// cons (optional) - regex with character list to be replaced, must have 1 group
// char (optional) - character to insert between duplicated cons
cons = cons || /([bcdfghjklmnpqrstvwxz])/ig; // excluding y by default
char = char || 'o';
return text.replace(cons, '$1' + char + '$1');
}
console.log(translate("this is fun"));
答案 1 :(得分:0)
function checkConsonants(letterToCheck) {
var consonants = ['b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y', 'z'];
var isConsonant = false;
for (i = 0; i < consonants.length; i++) {
if (letterToCheck == consonants[i]) {
isConsonant = true;
}
}
return isConsonant;
}
function translate(funString, letterO) {
console.log('The original string is: "' + funString + '"');
console.log('The separator is: "' + letterO + '"');
var newString = '';
for (var i = 0; i < funString.length; i++) {
if (checkConsonants(funString[i])) {
newString += funString[i] + letterO + funString[i];
} else {
newString += funString[i];
}
}
console.log('The "rövarspråket" result is: ' + '"' + newString + '"');
}
translate('this is fun', 'o');
看看这个。
答案 2 :(得分:0)
我会尝试使用最少量的代码,同时考虑到单词开头的大写字母......
function translate(fullString) {
cons=new Array("b","B","c","C","d","D","f","F","g","G","h","H","j","J","k","K","l","L","m","M","n","N","p","P","q","Q","r","R","s","S","t","T","v","V","w","W","x","X","y","Y","z","Z");
for(x in cons) {
fullString=fullString.replace(new RegExp(cons[x], 'g'), cons[x] + "o" + cons[x].toLowerCase());
}
return fullString;
}
我确信对我有更好的正则表达能力的人也可以减少数组的大小: - )