Adit A. Pillai Adit A. Pillai - 26 days ago 5
Javascript Question

Script running into an infinite loop while trying to insert a character

I am trying to replace all the occurrences of this symbol ' (Single inverted comma) with \' (A slash and an inverted comma).

I want to ignore the first and the last inverted comma.


To put it in an another way, I am simply trying to insert a slash before the '



Sample input: 'hello's world's'

Expected output: 'hello\'s world\'s'



I have written the following code but it seems to run into an infinite loop when I execute it.

What am I doing wrong?

And is there a more efficient way of getting it done?

text = "'hello's world's'";
for(i=text.indexOf("'") ; i<text.lastIndexOf("'");i++ )
{
if(text[i]=="'")
{
text=text.substr(0,i)+ "\\" + text.substr(i);

}
}

Answer

Two problems...

First, you're starting at the index of the first quote, which you claim you want to skip. So instead of starting with:

i=text.indexOf("'")

start with:

i=text.indexOf("'") + 1

Second, and more to the point of the infinite loop, every time you add a character the last index of the last quote increases by 1. So you're forever adding slashes to the first quote and pushing the last quote further away.

So after the first loop it's:

"'hello\'s world's'"

then:

"'hello\\'s world's'"

then:

"'hello\\\'s world's'"

And so on, infinitely.

To address this, simply increment i again any time you encounter a match:

text=text.substr(0,i)+ "\\" + text.substr(i);
i++;

The idea here is that because you've modified the string, you need to further modify your placeholder in the string (i) to compensate.