Kumar Kumar - 1 year ago 91
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.

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download