Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/366.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在javascript中用正则表达式替换空格_Javascript_Regex - Fatal编程技术网

在javascript中用正则表达式替换空格

在javascript中用正则表达式替换空格,javascript,regex,Javascript,Regex,我在查找正则表达式以替换给定字符串中的所有空格时遇到问题: var test = '1 2 3 4'; alert(test.replace(/\s/, '')); 第一个空格被正确替换,但我想得到不带空格的字符串。在上面的例子中,我期望是“1234” “g”表示“global”您必须在正则表达式的末尾添加一个用于global的g标志: var test = '1 2 3 4'; alert(test.replace(/\s/g, '')); 查看上的“标志”,在末尾添加gtest.repl

我在查找正则表达式以替换给定字符串中的所有空格时遇到问题:

var test = '1 2 3 4';
alert(test.replace(/\s/, ''));
第一个空格被正确替换,但我想得到不带空格的字符串。在上面的例子中,我期望是“1234”


“g”表示“global”

您必须在正则表达式的末尾添加一个用于global的
g
标志:

var test = '1 2 3 4';
alert(test.replace(/\s/g, ''));

查看

上的“标志”,在末尾添加
g
test.replace(/\s/g',)
给出一个解释,而不仅仅是一个答案编辑:g代表全局:它将替换整个字符串,如果不是,它将只替换第一个出现的字符串AH ok。对,我忘了带旗子了。非常感谢。请按回答做标记;)
var test = '1 2 3 4';
alert(test.replace(/\s/g, ''));