Kumar Kumar - 8 months ago 55
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-")
being my string, as I came across in another post, it yields me

Any help would be greatly appreciated.

Thanks guys.


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