How to Split a String Breaking at a Particular Character in JavaScript

In this tutorial, you will find the easiest ways of splitting the string in small chunks breaking at a particular character.

For example, you have the following string:

jack brown~132 Street~Apt 20~New Jersey~NJ~12345

For splitting the strings, we should use the split() method like this:

let input = 'jack brown~132 Street~Apt 20~New Jersey~NJ~12345';
let fields = input.split('~');
let name = fields[0];
let street = fields[1];

According to ECMAScript6, the cleanest way is destructing arrays in the following way:

const INPUT = 'jack brown~132 Street~Apt 20~New Jersey~NJ~12345';
const [name, street, unit, city, state, zip] = INPUT.split('~');
console.log(name); // jack brown
console.log(street); // 132 Street
console.log(unit); // Apt 20
console.log(city); // New Jersey
console.log(state); // NJ
console.log(zip); // 12345

The split() Method

The split() method cuts the string into substrings, puts them into an array, and returns the array. The division is accomplished by searching for a pattern, where it is provided as the first parameter in the call of the method.

Do you find this helpful?

Related articles