正则表达式替换所有领先的空格

qwe*_*ymk 3 javascript regex replace

我试图用一些东西替换字符串中的所有前导空格

这是我到目前为止所尝试的内容

var str = '     testing    1   2   3    ',
    regex = /^\s*/,
    newStr = str.replace(regex, '.');

document.write(newStr)
Run Code Online (Sandbox Code Playgroud)

我想得到一个结果:

'.....testing    1   2   3    '
Run Code Online (Sandbox Code Playgroud)

有什么我想念的吗?

Bar*_*ers 13

试试这个:

var s = "   a b c";
print(s.replace(/^\s+/, function(m){ return m.replace(/\s/g, '.');}));
Run Code Online (Sandbox Code Playgroud)

打印:

...a b c
Run Code Online (Sandbox Code Playgroud)