Kumar Kumar - 8 days ago 5
Javascript Question

Insert a character after every n characters but only for the first x occurrences

I have a string of 13 characters say XXXXXXXXXXXXX. I wish to enter a hyphen after every three characters but only for the first three occurrences using JQuery and possibly Regular Expressions.

Which means I need my string to be XXX-XXX-XXX-XXXX.

If I use

str.replace(/(.{3})/g, "$1-")
,
str
being my string, as I came across in another post, it yields me
XXX-XXX-XXX-XXX-X
.

Any help would be greatly appreciated.

Thanks guys.

Answer

What about .replace(/(.{3})(.{3})(.{3})/,'$1-$2-$3-')?

Comments