开发者

regex replace all leading spaces with something

开发者 https://www.devze.com 2023-03-27 03:38 出处:网络
I\'m trying to replace all of the leading spaces in a string with something Here\'s what I tried so far

I'm trying to replace all of the leading spaces in a string with something

Here's what I tried so far

var str = '     testing    1   2   3    ',
    regex = /^\s*/,
    newStr = str.replace(regex, '开发者_JAVA技巧.');

document.write(newStr)

I want to get a result like:

'.....testing    1   2   3    '

Is there something I'm missing?


Try this:

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

which prints:

...a b c


Alternative (ignores strnigs w/ no non-space)

var newStr = "";
newStr = (newStr = Array(str.search(/[^\s]/) + 1).join(".")) + str.substr(newStr.length);


What about:

/^([ ]+)/

I'm not sure \s does the trick, while a plain should be able to handle this!


This is even shorter.

var text = "   a b c";
var result = s.replace(/\s/gy, ".");

console.log(result); // prints: "...a b c";

Why it works was explained for me here.

0

精彩评论

暂无评论...
验证码 换一张
取 消