Becky
Becky

Reputation: 5585

Add 3 spaces in a squence

I've got a 8 digits string. How can I add a space in the following sequesnce

var str = "11111111";
//expected output 1111 11 11 

Add a space after first 4 digits and then the next two digits and then before the last two digits.

I know to do a single space ( .replace(/[_]/g," ");). But how do I do 3 in the above sequence?

Upvotes: 0

Views: 54

Answers (2)

madox2
madox2

Reputation: 51871

You can use substring method:

var result = str.substring(0, 4) + " " + str.substring(4, 6) + " " + str.substring(6)

Upvotes: 2

potatopeelings
potatopeelings

Reputation: 41065

You could use a regular expression replace

"11111111".replace(/(....)(..)(..)/, '$1 $2 $3')

Upvotes: 7

Related Questions