WhatisSober
WhatisSober

Reputation: 988

Split a string into array from back

I have a string.

var string = "31415926535897932384626433832795028841971693993751058209749445923078164";

I want to split it into an array of length 10 from back.

I have:

function split(a) {
  return a.split( /(?=(?:..........)*$)/ ).map(function(x){return parseInt(x)});
}

which gives me the desired output as:

[3, 1415926535, 8979323846, 2643383279, 5028841971, 6939937510, 5820974944, 5923078164]

Questions:

Upvotes: 0

Views: 855

Answers (3)

Aniket Singh
Aniket Singh

Reputation: 2634

the easy way..without using RegExp var string="31415926535897932384626433832795028841971693993751058209749445923078164"; var arr = new Array(); while (!string.length < 10) { substr = string.substr(strlen(string)-10); string = string.replace(substr, ''); arr.push(substr); } var result_arr = arr.reverse();

Upvotes: 1

Avinash Raj
Avinash Raj

Reputation: 174696

Just specify the number of digits you want to get for each item inside curly braces. And note that you can't pass variable to the regex which uses / as delimiters. You have to use RegExp constructor to pass variables in regex.

var string = "31415926535897932384626433832795028841971693993751058209749445923078164";
function split(a,n) {
  return a.split( new RegExp("(?=(?:.{" + n + "})*$)" )).map(function(x){return parseInt(x)});
}
alert(split(string, 10))

OR

You may simply use match instead of split.

string.match(/(?!^.).{11}/gm)

DEMO

var string = "31415926535897932384626433832795028841971693993751058209749445923078164";
function split(a,n) {
  return a.match(new RegExp("(?!^.).{" + n + "}|^.", "gm")).map(function(x){return parseInt(x)});
}
alert(split(string, 11))

If you also want to match the remaining chars, ie, the char present at the start and the unmatched chars exists at the last, you may use this regex.

/(?!^.).{11}|^.|.+/gm

DEMO

Upvotes: 6

Harpreet Singh
Harpreet Singh

Reputation: 2671

Please check this

var _mySplit = function(str, splitLength) {
    var _regEx = '';
    var startSubStringLength = str.length % splitLength
    if(startSubStringLength > 0) {
        _regEx = new RegExp("(^.{1," + startSubStringLength + "})|(.{1," + splitLength +  "})|(.{1,})", "g")
    }
    return str.match(_regEx)
}

Upvotes: 1

Related Questions