qwertymk
qwertymk

Reputation: 35304

regex replace all leading spaces with something

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, '.');

document.write(newStr)

I want to get a result like:

'.....testing    1   2   3    '

Is there something I'm missing?

Upvotes: 4

Views: 6863

Answers (4)

ThdK
ThdK

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

Bart Kiers
Bart Kiers

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

Alex K.
Alex K.

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

cutsoy
cutsoy

Reputation: 10251

What about:

/^([ ]+)/

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

Upvotes: 0

Related Questions