Split a string breaking at a particular character in JavaScript

In this article, we will how to split a string at a particular character in JavaScript. We shall demonstrate this using two different techniques.

  • split() function.
  • using for loop.

Using split() function:

In this method, you can pass the particular character from where you want to break the strings. It divides the string into substrings, adding them to the array and returning the array of substrings.

Example 1:

Here, we print the array after splitting and try to access the elements.

const INPUT = 'This is-code speedy-article-Hetvi Jain';
const consArray = INPUT.split('-');
console.log(consArray); 
console.log(consArray[0]); 
console.log(consArray[1]); 

Output:

[ 'This is', 'code speedy', 'article', 'Hetvi Jain' ]
This is
code speedy

Example 2:

This is another way of deconstructing the array and printing the substring.

const INPUT = 'This is+code speedy+article+Hetvi Jain';
const [sentence, website,article, name] = INPUT.split('+');
console.log(sentence); 
console.log(website); 
console.log(article); 
console.log(name);

Output:

This is
code speedy
article
Hetvi Jain

Using For loops:

If we don’t want to use the split function, we can also split the string at a particular character using for loop. Each iteration of for loop will check for a particular character and if the particular character matches we will split the string at that particular position.

Example:

const INPUT = 'This is,code speedy,article,Hetvi Jain';
let splitChar=","
let finalArr=[]; // final splitted array
let splitString="";
for(var x=0;x<INPUT.length;x++){
    if(INPUT[x]===splitChar){
 finalArr.push(splitString);
        splitString="";
    }else{
        splitString+=INPUT[x];
    }
}
if(splitString.length>0){
    finalArr.push(splitString); 
}
console.log(finalArr)
console.log(finalArr[0])

Output:

[ 'This is', 'code speedy', 'article', 'Hetvi Jain' ]
This is

These are a few ways you can split a string at a particular character.

Leave a Reply

Your email address will not be published. Required fields are marked *