How to split string without using JS's inbuilt spit function
Tags: codenewbie, javascript
Published: 2020-10-10 12:04:34

Hey fellow devs, this is my first dev blog post and today I will be cover one of the most commonly asked interview question

**How to split the string without using JS's inbuilt split function?**

##Process

I will mark numbers at each step in the program and will explain in detail what is happening.

```javascript

    const splitString = (str) => {
      let resultArray = [];              //1
      let tempString = '';               //2
      for(var i = 0; i< str.length;i++){ //3
          if(str[i] !== ' '){            //4
            tempString += str[i];        //5
           } else{                       
            resultArray.push(tempString);//6
            tempString = "";             //7
          }
      }
      return resultArray;                //8
   }

```

1. In the first step we are simply declaring an empty array where we will store our split values later.

2. here, we are declaring an empty string which will be used later.

3. In the 3rd step we are going to loop over the string provided via the argument, We will start at index(i=0) and our stopping condition will be the Total length of the string(str.length) e.g, our loop will run until the index value is less than the length of the string.

4. Here, we are putting a check using the if statement and checking whether the current iteration element is an empty character or not, if it is not an empty character we are moving to step 4.

5. here we will use the tempString string that we declared earlier.
if the present iteration character in the loop is not an empty character then we will append that character to the tempString.
if the present iteration character is empty char(' ') then we move to the else clause(step 6).  

6. Now that we have a string without empty space we can use the array push method to push this formed string into our resultArray.
Since this is our first iteration and if we provide the string "Front end dev" then the "Front" word has now been pushed into the array and we move onto the next step.

7. In this next step we will set the tempString to empty because we want the next iteration to start with a fresh empty string otherwise, the next iteration will put the previous string again in the array.

8. Return the resultArray.

**Loop will iterate until there are no words left in string**

Let's look at the result if we run this function with the string 
"dev life is cool"

```javascript
//input
const testString = "dev life is cool";
splitString(testString);

//output
["dev", "life", "is"]

```
Hmmm... what happened here?🧐 you might wonder.
well, you have every right to, the last word is not being added to the array and we have to make some adjustments in our code.
this is happening because in our step 4 the if statement checks for an empty character(' ') but there is no empty space after the last word "cool" is our testString so it does not add the last word.
we will modify our code like this and add an extra step some minor changes I will show:
```javascript

    const splitString = (str) => {
      let resultArray = [];              
      let tempString = '';               
      for(var i = 0; i< str.length;i++){ 
          if(str[i] !== ' '){            
            tempString += str[i];        
           } else if(tempString.trim()){     //minor change                  
            resultArray.push(tempString);
            tempString = "";             
          }
      }
      if(tempString){                      //new step
         resultArray.push(tempString);    
      }
      return resultArray;                
   }

```

##Explaination

**Minor step**
I added the trim method to tempString because if in any case user provides a string with multiple spaces between words then this will eliminate them.

**New Step**
Nothing special in the new step, I just added an extra check because the whole string is being iterated over and that includes the last word also so in case if any word is remained in tempString just push that also to our resultArray.

Now our program will give the desired output. 

**GO CHECK!!!**

```javascript
//input
const testString = "dev life is cool";
splitString(testString);

//output
["dev", "life", "is", "cool"]

```
There are many methods to do this but this is how I did it, suggestion is always welcome if you guys have other ideas about how I can refactor this code better.

Happy Hacking🥳