2017-07-18 55 views
1

出于某种原因,这使得我的网页卡住,没有显示alert卡住我的网页在一些字符串没有错误

我想在一些文本与\"更换"

示例参数

Search = "

Replace = \"

Text = "hello world"

Text"hello world"没有牛逼hello world

预期输出(Text)应\"hello world\"

var Search = prompt("What To Search?"); // It will be the sign " 
 
var Replace = prompt("What Sign To Replace?"); // It will be the sign \" 
 
var Text = prompt("Write Text Here"); 
 
while(Text.includes(Search)) 
 
{ 
 
    Text=Text.replace(Search,Replace); 
 
} // It's didn't replace all so I did this 
 
alert(Text);

回答

2

它卡住,因为你是一个无限循环

使用此

String.prototype.replaceAll = function(search, replacement) { 
    var target = this; 
    return target.split(search).join(replacement); 
}; 

var Search=prompt("What To Search?"); // It will be the sign " 
var Replace=prompt("What Sign To Replace?"); // It will be the sign \" 
var Text=prompt("Write Text Here"); 

      Text=Text.replaceAll(Search,Replace); 

alert(Text); 

现在尝试

Text=Text.replaceAll(Search,Replace); 

,而不是

Text=Text.replace(Search,Replace); 

See working Example here

2

它卡住,因为你是一个无限循环下去,因为你创造你与更换相同的字符串你的替换声明。

你可以使用替换为其他答案中给出的,你也可以使用split和join的组合来做到这一点。

var Search = prompt("What To Search?"); // It will be the sign " 
 
var Replace = prompt("What Sign To Replace?"); // It will be the sign \" 
 
var Text = prompt("Write Text Here"); 
 
Text = Text.split(Search).join(Replace); 
 
alert(Text);

+0

那么你有一个解决方案? – casraf

+0

@casraf正在研究解决方案,现在已更新。 – Dij

2

好吧,如果你与另外一个包含它,while循环的条件替换字符串将保持真实,显然它会不断循环并不会停止......你使用正则表达式来全局替换,这意味着它马上就会全部替换:

var Search = prompt("What To Search?"); // It will be the sign " 
 
var Replace = prompt("What Sign To Replace?"); // It will be the sign \" 
 
var Text = prompt("Write Text Here"); 
 
Text = Text.replace(new RegExp(Search, 'g'), Replace); 
 
alert(Text);

当然,您可能希望在某些情况下执行文本的验证或转义

2

原因是您要用相同的字符串替换字符串。所以while循环将永远成为真实。 你可以简单地使用正则表达式这里

var re = new RegExp(Replace, 'g'); 
Search = Search.replace(re,Text); 

Here是对的jsfiddle你

相关问题