I have a text that contains the word “be” which I want to replace with the word “feel”. When I use indexOf I manage to replace only the first instance. I tried to do it with loop to replace all “be” instances but it didn’t work. Can someone advice how can it be done right with loop statement?
var seg = "to be or not to be"
var limit = seg.length;
var firstChar = seg.indexOf("be");
if (firstChar !== -1) {
seg = seg.slice(0, firstChar) + "feel" + seg.slice(firstChar + 2);
}
console.log(seg);
var seg = "to be or not to be"
var limit = seg.length;
var firstChar = seg.indexOf("be");
while (firstChar !== -1) {
seg = seg.slice(0, firstChar) + "feel" + seg.slice(firstChar + 2);
}
console.log(seg);
also, when i try to run a loop i get a really weird results, any ideas why?
var seg = "to be or not to be"
var limit = seg.length;
var firstChar = seg.indexOf("be");
for (var i = 0; i < limit; i++) {
if (firstChar !== -1) {
seg = seg.slice(0, firstChar) + "feel" + seg.slice(firstChar + 2);
}
}
console.log(seg);
You’re getting weird results because you set the firstChar index before the loop, but never update it afterward. Every single iteration of your loop is altering the same index.
Set or update firstChar within your loop and you’ll get viable results. I can add a sample if you need, but I’m confident you’ve got it (unless I’ve just been terribly unclear, in which case my apologies).
No, don’t run that code, you’ll get infinite loop with it!
Why? Because you wrote var firstChar = seg.indexOf("be"); outside of the while loop and it doesn’t update itself with each loop, so the value of firstChar in this case will always greater than -1, and your code will never stop running.
You can rewrite your code like this
let seg = "to be or not to be";
let firstChar = seg.indexOf("be");
while (firstChar !== -1) {
seg = seg.slice(0, firstChar) + "feel" + seg.slice(firstChar + 2);
firstChar = seg.indexOf("be");
}
console.log(seg);