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

regex - javascript split string at at two different indexes - Stack Overflow

programmeradmin4浏览0评论

I have a credit card # for amex I.E. 371449635398431 that I'd like to split up into 3 parts 3714 496353 98431 - Is there an easy way to split a string up by predefined indexes (in this case 4 & 10), possibly with a simple regex function?

I have a credit card # for amex I.E. 371449635398431 that I'd like to split up into 3 parts 3714 496353 98431 - Is there an easy way to split a string up by predefined indexes (in this case 4 & 10), possibly with a simple regex function?

Share Improve this question asked Jul 20, 2013 at 4:00 CoreyCorey 8453 gold badges13 silver badges21 bronze badges 0
Add a ment  | 

4 Answers 4

Reset to default 10

I don't really see the need for regular expressions here. If you know the indexes you need to split on, you can just do this:

var input = '371449635398431'
var part1 = input.substr(0, 4);
var part2 = input.substr(4, 6);
var part3 = input.substr(10);

But if a regular expression is a must, you can do this:

var input = '371449635398431'
var match = /^(\d{4})(\d{6})(\d{5})$/.exec(input);
var part1 = match[1];
var part2 = match[2];
var part3 = match[3];

To insert spaces between each part you can do this:

var match = input.substr(0, 4) + ' ' + input.substr(4, 6) + ' ' + input.substr(10);

Or this:

var match = [ input.substr(0, 4), input.substr(4, 6), input.substr(10) ].join(' ');

Or this (inspired by Arun P Johny's answer):

var match = /^(\d{4})(\d{6})(\d{5})$/.exec(input).slice(1).join(' ');

Or this:

var match = input.replace(/^(\d{4})(\d{6})(\d{5})$/, '$1 $2 $3');

Try

var array = '371449635398431'.match(/(\d{4})(\d{6})(\d{5})/).splice(1)

Here I improve p.s.w.g answer by using slice instead substr (input string in s)

[s.slice(0,4), s.slice(4,10), s.slice(10)]

let s="371449635398431"; 
let a=[s.slice(0,4), s.slice(4,10), s.slice(10)]

console.log(a);

Below I simplified regex used in answers Arun P Johny and p.s.w.g

'371449635398431'.match(/(.{4})(.{6})(.{5})/).splice(1)

var a = '371449635398431'.match(/(.{4})(.{6})(.{5})/).splice(1);

console.log(a);

发布评论

评论列表(0)

  1. 暂无评论