How to split a string in JavaScript with built-in and custom function

In this tutorial, we will learn how to split a string into an array of substrings in JavaScript.

Splitting a string in JavaScript

Variables used in code

  • str – the string that will be split.
  • splitBy -the string splitBy is used as a separator.
  • limit – the number of splits is determined by the limit.
const str = "This is a Tutorial in CodeSpeedy"
const splitBy = " "
const limit = 3

Method 1: Split string with built-in function in JavaScript

We’re going to use the built-in function split() in this method.

let split = str.split(splitBy)
console.log(split)
split = str.split(splitBy,limit)
console.log(split)

Output

["This", "is", "a", "Tutorial", "in", "CodeSpeedy"]
["This", "is", "a"]

Method 2: split string without built-in function in JavaScript

I wrote the custom function instead of using the built-in spilt() function to split a string.

InBuilt Functions used 

  • indexOf(subString,start) – returns the subString’s index from the start position in the string.
  • push(element) – adds the element to the end of the array.
  • slice(start,end) – returns a subarray (characters starting from start to end-1 from the string).
function splitFunction(str,splitBy,limit){
    let arr = []
    let i = 0
    const n = splitBy.length!==0 ? splitBy.length : 1 
    const m = splitBy.length!==0 ? 0 : 1 
    while(i!==-1 & i<=str.length){
        if (limit!==null & limit<=0){
    	    break
        }
  	index = str.indexOf(splitBy,i)
        if (index!==-1){
    	    arr.push(str.slice(i,index+m))
            i = index + n
        }
        else{
    	    arr.push(str.slice(i))
            i = index
        }
        if (limit!==null) limit-= 1
    }
    return arr
}

let split = splitFunction(str,splitBy)
console.log(split)
split = splitFunction(str,splitBy,3)
console.log(split)

Output

["This", "is", "a", "Tutorial", "in", "CodeSpeedy"] 
["This", "is", "a"]

Also read: JavaScript string replace() method | Replace string part

Leave a Reply

Your email address will not be published.