Reputation: 988
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:
How do I make the above function dynamic so I can break strings to n number of characters? (Currently I am adding/removing dots)
How do I skip the first character when splitting? (I would like first element to be always 3 so second element can be of length 1 to n)?
Upvotes: 0
Views: 855
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
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)
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
Upvotes: 6
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