Write a function translate() that will translate a text into "rövarspråket". That is, double every consonant and place an occurrence of "o" in between. For example, translate("this is fun") should return the string "tothohisos isos fofunon"
-
1As a swede I approve of this function.– Henrik AnderssonCommented Jan 8, 2015 at 11:32
-
2this site is for seeking answers to specific problems with existing pieces of code. It does not exist to tell you how to write the code in the first place.– AlnitakCommented Jan 8, 2015 at 11:34
-
One approach would be to loop over the characters in the input string, check if each one is a consonant or not, then do the right thing. By the way, could you give your question a title saying what it's actually about?– user663031Commented Jan 8, 2015 at 11:38
Add a comment
|
3 Answers
Simple regex replacement - but you need to decide for yourself whether you want to treat Y
as a vowel or as a consonant:
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"));
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');
Take a look of this.
I'll go for attempting the minimum amount of code while also taking uppercase letters at the beginning of words into account...
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;
}
I'm sure someone with a better knowledge of regex than me could also reduce the size of the array :-)