How to Split String at Specific Character in JavaScript

To split a string at a specific character in JavaScript, you can the “split()” function. The split() method takes a “separator” as its argument, a string or a regular expression, and returns the new array.

If (” “) is used as a separator, the string is split between words. If the separator is not found in the input string, the method returns an array containing the entire input string as its single element.

Syntax

str.split(",");

Example: Using string.split() Method

const inputString = 'nshah@gmail.com';
const separator = '.';

const resultArray = inputString.split(separator);

console.log(resultArray);

Output

['nshah@gmail', 'com']

In this example, we used the split() method to break the inputString into an array of substrings, using the separator variable (‘.’) as the delimiter. The resulting array contains two elements: ‘nshah@gmail‘ and ‘com’.

JavaScript’s array destructuring in combination with the split() method

JavaScript array destructuring is a neat and compact way of parsing a string into multiple variables in a single line of code.

const input_string = 'Jane~456 Boulevard~Unit 18~Los Angeles~CA~54321';

const [your_name, address, apartment, city, state, zipCode] = input_string.split('~');

console.log(your_name);
console.log(address);
console.log(apartment);
console.log(city);
console.log(state);
console.log(zipCode);

Output

Jane
456 Boulevard
Unit 18
Los Angeles
CA
54321

That’s it.

Leave a Comment