1

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.

4
  • You can use String.prototype.split with a regular expression, or loop and count characters.
    – elclanrs
    Commented Apr 14, 2014 at 8:53
  • 3
    why split()?, use substring(). Commented Apr 14, 2014 at 8:54
  • there is not a specific reason. I think split can solve it
    – barteloma
    Commented Apr 14, 2014 at 8:56
  • Its is subjective to length.So, regex will be even more simpler - /[a-zA-Z]{1,3}/gi. Given below with more explanation.
    – vivek_nk
    Commented Apr 14, 2014 at 9:38

4 Answers 4

1
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
0

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>
0

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.

4
  • Question is: Do you really want the vm to create a whole state machine to simply split a string?
    – niklasfi
    Commented Apr 14, 2014 at 9:21
  • there's a typo in your title
    – niklasfi
    Commented Apr 14, 2014 at 9:22
  • @niklasfi Is this too complicated? And this has nothing related with state machine...
    – xdazz
    Commented Apr 14, 2014 at 9:26
  • a regex parser is nothing but a finite state machine
    – niklasfi
    Commented Apr 14, 2014 at 9:40
0

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"]
1
  • See the desired output of the question.
    – xdazz
    Commented Apr 14, 2014 at 9:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.