Javascript 字符串方法替换无法正常工作

Javascript 字符串方法替换无法正常工作,javascript,jquery,Javascript,Jquery,我正在使用字符串的replace方法 var text = this ex is not working.; text = text.replace(" ", "+"); alert(text); 并得到警告: this+ex is not working. 这里有什么问题?要使用加号字符替换所有空格,请使用以下命令: var text = "this ex is not working."; text = text.replace(/ /g, "+"

我正在使用字符串的
replace
方法

     var text = this ex is not working.;
     text = text.replace(" ", "+");
     alert(text);
并得到警告:

     this+ex is not working.

这里有什么问题?

要使用加号字符替换所有空格,请使用以下命令:

var text = "this ex is not working.";
text = text.replace(/ /g, "+");
alert(text);

不要忘记使用引号
初始化字符串。

要使用加号
+
字符替换所有空格,请使用以下命令:

var text = "this ex is not working.";
text = text.replace(/ /g, "+");
alert(text);

不要忘记使用引号
初始化字符串。

试试这个:lil diff demo

请注意:

RegExp上的g标志,它将在 绳子

如果你喜欢:

Rest可以随意使用演示,
:)

代码

var text = "this ex is not working.";
     text = text.replace(/\s+/g, '+');
     alert(text);​

试试这个:lil diff演示

请注意:

RegExp上的g标志,它将在 绳子

如果你喜欢:

Rest可以随意使用演示,
:)

代码

var text = "this ex is not working.";
     text = text.replace(/\s+/g, '+');
     alert(text);​

对于新手来说,这个答案比前一个答案提供的信息要多一些。投票支持这个答案。@NikolayZakharov很高兴你喜欢它,祝你玩得开心,再见。:)这个答案对新手来说比前一个答案更有用。投票支持这个答案。@NikolayZakharov很高兴你喜欢它,玩得开心,再见。:)