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!