Reputation: 105
I am trying to use the following code to replace all the vowels from a string but it only works using regex. How can I use for of iteration?
// THIS DOES NOT WORK
newStr = '';
for (const c of "aeiou") {
console.log(c);
newStr = 'Hello World'.replace(c, '*');
}
console.log(newStr); // Prints Hello World to the console
// ONLY THIS WORKS
newStr = 'Hello World'.replace(/[aeiou]/g, '*');
console.log(newStr);
Upvotes: 2
Views: 477
Reputation: 735
You can do it this way:
var newStr = 'Hello World';
for (let a of newStr) {
for (let b of "aeiou") {
if (a === b) {
newStr = newStr.replace(a, '*');
}
}
}
console.log(newStr);
Upvotes: 0
Reputation: 382
Try this instead:
let newStr = 'Hello World';
for (const c of "aeiou") {
while (newStr.indexOf(c) > -1)
newStr = newStr.replace(c, "*");
}
console.log(newStr); // Prints Hello World to the console
string.prototype.replace only replaces the first occurrence of c in newStr. string.prototype.replace
Upvotes: 0
Reputation: 282160
The issue with your code is that in for loop everytime youare trying to replace on "Hello World" string and assign the result to newStr. However in the last iteration you check for u, since u is not presetn in Hello World, the entire string gets assigned as such to newStr.
You should instead initialise newStr to "Hello World" and then perform replace on it
var newStr = 'Hello World';
for (const c of "aeiou") {
console.log(c);
newStr = newStr.replace(c, '*');
}
console.log(newStr);
However note that this will only replace one instance of the matching character and not all of them, You will still need to use regex
newStr = newStr.replace(new RegExp(c, 'g'), '*');
var newStr = 'Hello World';
for (const c of "aeiou") {
newStr = newStr.replace(new RegExp(c, 'g'), '*');
}
console.log(newStr);
or split and join the string
newStr = newStr.split(c).join('*');
var newStr = 'Hello World';
for (const c of "aeiou") {
newStr = newStr.split(c).join('*');
}
console.log(newStr);
String.prototype.replaceAll
on string
Upvotes: 1
Reputation: 17620
use split
, join
as a way if you don't want to use regex
newStr = 'Hello World';
for (const c of "aeiou") {
console.log(c);
//newStr = 'Hello World'.replace(c, '*');
newStr = newStr.split(c).join('*');
}
console.log(newStr); // Prints Hello World to the console
// ONLY THIS WORKS
newStr = 'Hello World'.replace(/[aeiou]/g, '*');
console.log(newStr);
Upvotes: 2