How do I split a string by a separator, preferably whitespace, and put it into an array? [SOLVED]

0 favourites
  • 3 posts
From the Asset Store
This collection of music is the beautiful performance of rather small strings ensemble (8 first violins, 6 second violin
  • I am looking for a way to split a string by whitespace separator and put it into an array in construct.

    I would like to be able to split user's string input into an array. Separator must take into account whitespace " ".

    There is a split function in javascript that does it right of the bat.

    This is partly what i would need

    var str = "How are you doing today?";

    var res = str.split(" ");

    output:

    How,are,you,doing,today?

    But still i would need it in an array [how, are, you, doing, today?] == this is my desired output.

    I have found a way the split function is built here:

    function CustomSplit(str, delimiter, removeEmptyItems) {
     if (!delimiter || delimiter.length === 0) return [str];
     if (!str || str.length === 0) return [];
     var result = [];
     var j = 0;
     var lastStart = 0;
     for (var i=0;i<=str.length;) {
     if (i == str.length || str.substr(i,delimiter.length) == delimiter)
     {
     if (!removeEmptyItems || lastStart != i)
     {
     result[j++] = str.substr(lastStart, i-lastStart);
     }
     lastStart = i+delimiter.length;
     i += delimiter.length; 
     } else i++;
     }
     return result;
    }
    

    alert(JSON.stringify(CustomSplit("how do you do", ",", true)));

    alert(JSON.stringify(CustomSplit("c$?as$?$?a$cc$?", "$?", true)));

    the code to run is here:

    jsfiddle.net/S5Wy7

    found it here

    stackoverflow.com/questions/24765710/writing-a-string-splitting-function-without-using-the-split-method-in-javascript

    Unfortunately it is not granular enough, because it uses a different function, namely:

    str.substr(i,delimiter.length)
    
    

    I got stuck looking for a way to build a granular str.substr().

    However, maybe there is an easy way to split a string by whitespace separator and put it into an array in construct?

    Please help!

  • Try Construct 3

    Develop games in your browser. Powerful, performant & highly capable.

    Try Now Construct 3 users don't see these ads
  • See tokenat and tokencount expressions:

    scirra.com/manual/126/system-expressions

    Repeat (tokencount(text, " ")-1) times
    	Array set at loopindex value: tokenat(text, loopindex, " ")
    
  • dop2000> I love Construct 3!, you are ingenious and your suggestion is remarkable.

Jump to:
Active Users
There are 1 visitors browsing this topic (0 users and 1 guests)