Jonny Smyth Jonny Smyth - 3 months ago 14
Javascript Question

split up string with delimiter only using basic language(if,for,while etc)

i have the function:

//this function takes two params, a string and then the delimiter where the string is to be split up
function substringSplit(str, del){
var str;
var del;
for(var i=0;i<str.length;i++){
if(!str[i]==del){
var res = str[i];
console.log(res);
}
}


and what i am trying to achieve is splitting up a string e.g "the house is there" with a delimiter i.e " ", however my code isnt doing this properly!

does any one have any suggestions?

ps the idea is to not use another functions i.e split().

Answer

your code would be printing out one by one all the characters that are not equal to the delimiter. So if my call was:

substringSplit("hi tom"," ");

Your program would print:

h
i
t
o
m

this could be a possible algorithm to achieve what you want:

function substringSplit(str, del){
    var splitArray = [];
    for(var i=0;i<str.length;i++){
        var newWord = "";
        while(str[i]!=del && i < str.length) {
            newWord += str[i];
            i++;
        }
        splitArray.push(newWord);
    }
    return splitArray;
}

I have not tested boundary conditions, so don't take this as perfect but maybe just a base to start with.