Reputation: 6875
I want to separete this text with split function like this. Array items should be 3 charecters.
var text = "abcdef";
var splitted = ["abc", "def"]
var text = "abcdefg";
var splitted = ["a", "bcd", "efg"]
var text = "abcdefgk";
var splitted = ["ab", "cde", "fgk"]
text split from last to first.
Upvotes: 1
Views: 319
Reputation: 1600
For the desired output, we need to use substring, since the smaller section is taken at beginning than at end. Note: we do not use slice, because negative index in slice will take characters from string from end again. So, we stick with substring to avoid that.
var str = "abcdefgh";
var len = str.length;
var res = [];
for(var i=len;i>0;i=i-3){
res.push(str.substring(i-3,i));
}
//res array will contain the desired output now
But, if parsing should be greedy form beginning, i.e. {3,3,2} instead of {2,3,3} then, use the regex (/[a-zA-Z]{1,3}/gi ) for this,which is easier and faster.For this we do not need substring. var str = "abcdef"; var result = str.match(/[a-zA-Z]{1,3}/gi); //["abc","def"]
var str = "abcdefgh";
var result = str.match(/[a-zA-Z]{1,3}/gi); //["abc","def","gh"]
var str = "abcdefg";
var result = str.match(/[a-zA-Z]{1,3}/gi); //["abc","def","g"]
Upvotes: 0
Reputation: 160963
Regex solution:
var text = "abcdefg";
var regex = text.length % 3 ? '^.{'+ (text.length % 3) +'}|.{3}' : '.{3}';
var result = text.match(new RegExp(regex, 'g'));
// ["a", "bcd", "efg"]
You could also do with:
var text = "abcdefg";
var result = [text.substr(0, text.length % 3)].concat(text.substr(text.length % 3).match(/.{3}/g));
Hint: consider .match
instead of .split
to get the result when using regex.
Upvotes: 0
Reputation: 3840
If you want to use recursion then try this
<script type="text/javascript">
function strSplit(str){
var arr=[];
dorecurSplit(str,str.length,arr,0);
alert(arr);
}
function dorecurSplit(st,len,ar,x)
{
if(len<=0)
return ar;
else{
var i=len%3;
if(i==0)
{
ar.push(st.substring(x,x+3));
dorecurSplit(st,len-3,ar,x+3);
}
else
{
ar.push(st.substring(x,i));
dorecurSplit(st,len-i,ar,x+i);
}
}
}
</script>
to call this
<button onclick="strSplit('abcdefghij')">Split it</button>
Upvotes: 0
Reputation: 15961
var size = 3; //specify the size here
var str = "abcdefgk" //the string you want to split
var i = str.length % 3; // modulo gets you the remaining part
var result = [str.substring(0,i)]; //create array with only first part
//for the rest, iterate over str and add chunks of length size
for(; i < str.length; i+=size){
result.push(str.substring(i, i+size))
}
alert(result) //display the result
Upvotes: 1