把我的页面粘在一些字符串上没有错误

时间:2017-07-18 12:25:11

标签: javascript

出于某种原因,这会导致我的页面卡住并且不会显示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);

4 个答案:

答案 0 :(得分: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

答案 1 :(得分: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);

答案 2 :(得分: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);

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

答案 3 :(得分:2)

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

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

Here对你来说是个傻瓜