Using indexOf with loop

Hello,

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);

Hi, I think in this case you can use while loop (replace it until no match is found).
Still, regex and replace seems to be be a more simple solution.

Like @tkhquang suggests:

while ((nextIndex = seg.indexOf("be")) > -1) {
  seg = seg.slice(0, nextIndex) + "feel" + seg.slice(nextIndex + 2);
}

Definitely would be cleaner using regex.

EDIT: Realized I had posted the wrong code, so I have corrected it.

thanks @tkhquang

so if i was to use while it would be like this?


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).

so if i was to use while it would be like this?

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);
1 Like

Thanks mate I got it!

Thanks @tkhquang I understand now what went wrong.