尝试插入字符时脚本运行到无限循环

时间:2016-11-11 13:32:21

标签: javascript infinite-loop

我正在尝试用 \' (斜线和倒置的逗号)替换此符号' (单个倒置逗号)的所有匹配项)。
我想忽略第一个和最后一个倒置的逗号

换句话说,我只想在' 之前插入一个斜杠

示例输入:' hello's world'
预期输出:' hello's world's'

我编写了以下代码,但是当我执行它时似乎遇到了无限循环。

我做错了什么?

是否有更有效的方法来完成它?

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

    }
}

4 个答案:

答案 0 :(得分:2)

通常情况下,您可以使用replace()函数执行此操作:

text.replace(/'/g,"\\'");

但是,由于您要忽略第一个和最后一个反转的逗号,请尝试以下代码:

text = "'hello's world's'";
first = text.indexOf("'");
last = text.lastIndexOf("'");
for (i=0; i < text.length - 1; i++)
{

  if (text[i] == "'" && i != first && i != last)
  {
        text = text.substr(0,i) + "\\" + text.substr(i);
        i++;
    }
}

答案 1 :(得分:2)

在这里,我试图检查字符是否是&#34;&#39;&#34;&#34;&#34;然后只需添加&#34; \&#34;我已经采取了新的结果。

每次我都会对数组进行切片,最后从0到指数&#39;&#39;&#39;&#39;并添加&#34; //&#34;对于这个切片的字符串,下一个切片索引从之前的索引&#34;&#39;&#34; +1增加到当前索引&#34;&#39;&#34;&#34; ,这一直持续到字符串的长度

&#13;
&#13;
var text = "'hello's world's'";
var delimeter = "\\";
var result = "";
var newindex = 0;
for (var i = 0; i < text.length; i++) {
  if (text[i] == "'") {
    var str = text.slice(newindex, i);
    result += "\\" + str;
    newindex = i + 1;
  }
}
console.log(result);
&#13;
&#13;
&#13;

希望有所帮助

答案 2 :(得分:1)

两个问题......

首先,您从第一个引号的索引处开始,您声称要跳过该索引。所以不要以:

开头
i=text.indexOf("'")

从:

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

其次,更多的是无限循环,每次添加一个字符时,最后一个引号的最后一个索引增加1.所以你永远在第一个引号中添加斜杠并推送最后一个引号更远的地方。

所以在第一次循环之后它是:

"'hello\'s world's'"

然后:

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

然后:

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

等等,无限。

要解决此问题,只需在遇到匹配时再次增加i

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

这里的想法是,因为您已修改字符串,您需要在字符串(i)中进一步修改占位符以进行补偿。

答案 3 :(得分:1)

在这种情况下,正则表达式有很多帮助。

text = "'hello's world's'";    
newText = text.replace(/(?!^)'(.*?)(?!$)/g,"\\'");
console.log(newText);

这是正则表达式测试 - https://regex101.com/r/9BXvYR/1

正则表达式排除了'并包括每个'的第一个和最后一个匹配

这就是吸虫 - https://plnkr.co/edit/eTqQ3fK9ELFyRNexGtJI?p=preview

相关问题