Hello,
I’m trying to complete an exercise question I found online:
“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’.”
I think I’m nearly there with it but I have an issue with a for loop I wondered if someone might be able to help me out with. Below is my code:
<body>
<p id="p1">this is my string</p>
<p id="p2"></p>
<script language="JavaScript" type="text/javascript">
var myString = document.getElementById("p1").innerHTML;
vowels = new Array("a","e","i","o","u");
for (var i = 0, j = myString.length; i < j; i++) {
var letter = myString.substring(i, i + 1);
for (var k = 0, m = vowels.length; k < m; k++) {
var vowel = vowels[k];
if (letter != vowel) {
letter = letter + "o" + letter;
}
}
document.getElementById("p2").innerHTML += letter;
}
</script>
</body>
When I run this code I get loads all of the characters in the string repeated loads of time with the ‘o’ in the middle? I’m thinking it might be to do with me altering the letter variable in the second for loop and the loop then using that letter value to run again?
What I really don’t get is, if I change the code so it does the opposite to what I want (add those extra characters if the letter is equal to a vowel) it works great? e.g.
if (letter == vowel) {
letter = letter + "o" + letter;
}
Please let me know if you need me to explain more?
Thanks