最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Insert a character after every n characters but only for the first x occurrences - Stack Overflow

programmeradmin4浏览0评论

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
 |  Show 1 more ment

2 Answers 2

Reset to default 8

What 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+
发布评论

评论列表(0)

  1. 暂无评论