Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript split string at at two different indexes

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?

like image 945
Corey Avatar asked Jul 20 '13 04:07

Corey


People also ask

How can I split a string into two JavaScript?

The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.

Can you split a string at an index?

To split a string at a specific index, use the slice method to get the two parts of the string, e.g. str. slice(0, index) returns the part of the string up to, but not including the provided index, and str. slice(index) returns the remainder of the string.

Can split take multiple arguments JavaScript?

To split a string with multiple characters, you should pass a regular expression as an argument to the split() function. You can use [] to define a set of characters, as opposed to a single character, to match.

How do you split a string with multiple separators?

Use the String. split() method to split a string with multiple separators, e.g. str. split(/[-_]+/) . The split method can be passed a regular expression containing multiple characters to split the string with multiple separators.


2 Answers

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');
like image 109
p.s.w.g Avatar answered Sep 21 '22 02:09

p.s.w.g


Try

var array = '371449635398431'.match(/(\d{4})(\d{6})(\d{5})/).splice(1)
like image 26
Arun P Johny Avatar answered Sep 22 '22 02:09

Arun P Johny