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.
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.
Share Improve this question edited Jun 28, 2013 at 7:14 Ian 51k13 gold badges104 silver badges111 bronze badges asked Jun 28, 2013 at 7:02 LalitLalit 8492 gold badges16 silver badges26 bronze badges 6- Why searching for a hard way? Use loop. – David Jashi Commented Jun 28, 2013 at 7:04
- Thanks for that David but I thought a RegEx will make my life easier :) – Lalit Commented Jun 28, 2013 at 7:05
- 3 What do you have so far? – icedwater Commented Jun 28, 2013 at 7:05
- Hi icedwater, I found a RegEx in another post that is something like str.replace(/(.{3})/, "$1-"). But that will yield a string like XXX-XXX-XXX-XXX-X – Lalit Commented Jun 28, 2013 at 7:08
- @Kumar You should always include that originally, so we know you've attempted something and aren't just telling us to solve it for you – Ian Commented Jun 28, 2013 at 7:09
2 Answers
Reset to default 8What about .replace(/(.{3})(.{3})(.{3})/,'$1-$2-$3-')
?
If you want to do it with Regex this could work...
// Not nice but works
var text = "XXXXXXXXXXXXX";
text.replace(/(...)(...)(...)(....)/g, "$1-$2-$3-$4");
// Result "XXX-XXX-XXX-XXXX" Chrome 27+