This is a simple program to replace the characters of a string with another using for loop and if statements. However, I was not getting the desired result I want to get. Here is the code:
var str1 = "Optimism is the key to victory"
var str2 = ""
for(let i=0; i<str1.length;i++){
if(str1[i] == "i"){
var temp = str1[i]
temp = "1"
str2 += temp
}
if(str1[i] == "e"){
var temp2 = str1[i]
temp2 = "3"
str2 += temp2
}
else{
str2 += str1[i]
}
}
console.log(str2)
The result is this: "Opt1im1ism 1is th3 k3y to v1ictory" Why does it add another 'i' after '1' and how do I remove it? (thanks for the response in advance!)
You have
if (...) {
...
}
if (...) {
...
}
else {
...
}
The first if is not chained with the later two blocks - whenever the first condition is fulfilled, one of the other conditions will necessarily be fulfilled as well, resulting in str2 being concatenated to twice in a single iteration instead of once.
Use else/if instead.
var str1 = "Optimism is the key to victory"
var str2 = ""
for (let i = 0; i < str1.length; i++) {
if (str1[i] == "i") {
var temp = str1[i]
temp = "1"
str2 += temp
} else if (str1[i] == "e") {
var temp2 = str1[i]
temp2 = "3"
str2 += temp2
} else {
str2 += str1[i]
}
}
console.log(str2)
More elegantly:
var str1 = "Optimism is the key to victory"
var str2 = ""
for (let i = 0; i < str1.length; i++) {
if (str1[i] == "i") {
str2 += "1"
} else if (str1[i] == "e") {
str2 += "3"
} else {
str2 += str1[i]
}
}
console.log(str2)
Or ditch the indicies, they aren't helping much:
var str1 = "Optimism is the key to victory"
var str2 = ""
for (const char of str1) {
if (char == "i") {
str2 += "1"
} else if (char == "e") {
str2 += "3"
} else {
str2 += char
}
}
console.log(str2)
Or even
const str1 = "Optimism is the key to victory"
const str2 = str1.replace(/[ie]/g, char => char === 'i' ? '1' : '3');
console.log(str2)
What your code does is create two separate if else blocks.
First if checks for i .
Second if-else checks for e or not e.
Now the character i satisfies the first if condition and second else condition. That is why the code in both blocks get executed when the character i is encountered.
Use else if
var str1 = "Optimism is the key to victory"
var str2 = ""
for(let i=0; i<str1.length;i++){
if(str1[i] == "i"){
var temp = str1[i]
temp = "1"
str2 += temp
}
else if(str1[i] == "e"){
var temp2 = str1[i]
temp2 = "3"
str2 += temp2
}
else{
str2 += str1[i]
}
}
console.log(str2)
You can easily achieve the result first split the string, and then map over the string array to replace it with a replacement string using dict and finally join the string to get the final result.
var str1 = "Optimism is the key to victory";
const dict = {
i: 1,
e: 3,
};
const result = str1
.split("")
.map((c) => (dict[c] ? dict[c] : c))
.join("");
console.log(result);