Jonny Smyth Jonny Smyth - 1 year ago 52
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++){
var res = str[i];

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 Source

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:


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];
    return splitArray;

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