Javascript split string with two different indices

I have a credit card # for amex IE 371449635398431 , which I would like to divide into 3 parts 3714 496353 98431 . Is there an easy way to split a string into predefined indexes (in this case 4 and 10), possibly with a simple regular function?

+5
source share
4 answers

I really don't see the need for regular expressions here. If you know the indexes that need to be broken, you can simply do this:

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

But if regex is required, 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 that:

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

Or this (inspired by Arun P Johny answer ):

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

Or that:

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

Try

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

Below I have simplified the regex used in the answers by Arun P Joni and pswg

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

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

Here I am improving the pswg answer using slice instead of 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); 
0
source

Source: https://habr.com/ru/post/1492422/


All Articles