Reputation: 35304
I'm trying to replace all of the leading spaces in a string with something
var str = ' testing 1 2 3 ',
regex = /^\s*/,
newStr = str.replace(regex, '.');
document.write(newStr)
I want to get a result like:
'.....testing 1 2 3 '
Is there something I'm missing?
Upvotes: 4
Views: 6863
Reputation: 10576
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.
Upvotes: 0
Reputation: 170288
Try this:
var s = " a b c";
print(s.replace(/^\s+/, function(m){ return m.replace(/\s/g, '.');}));
which prints:
...a b c
Upvotes: 15
Reputation: 175936
Alternative (ignores strnigs w/ no non-space)
var newStr = "";
newStr = (newStr = Array(str.search(/[^\s]/) + 1).join(".")) + str.substr(newStr.length);
Upvotes: 1
Reputation: 10251
What about:
/^([ ]+)/
I'm not sure \s
does the trick, while a plain should be able to handle this!
Upvotes: 0