Adit A. Pillai Adit A. Pillai - 1 year ago 68
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++ )
text=text.substr(0,i)+ "\\" + text.substr(i);


Answer Source

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:


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'"


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


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

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download