Split a String by Special Characters in JavaScript


Borislav Hadzhiev

Thu Nov 18 20212 min read

Split a String by Special Characters #

To split a string by special characters, call the split() method on the string, passing it a regular expression that matches any of the special characters as a parameter. The method will split the string on each occurrence of a special character and return an array containing the results.

const str = 'a.b-c=d/e_f'; const result = str.split(/[.\-=/_]/); // 👇️ ['a', 'b', 'c', 'd' ,'e' ,'f'] console.log(result);
If you're looking for a regular expression that matches all special characters, scroll down to the last example.

The only parameter we passed to the split method is a regular expression - a separator on which we want to split the string.

The forward slashes / / mark the beginning and end of the regular expression.

The square brackets [] are called a character class and match any of the characters between the brackets. You could adjust the characters to your needs.

The regular expression in the example matches a dot, hyphen, equal sign, forward slash and underscore.

Some characters, e.g. hyphens, or backslashes have to be escaped because they have a special meaning.
const str = 'z=a-b\\c'; const result = str.split(/[=\-\\]/); // 👇️ ['z', 'a', 'b', 'c'] console.log(result);

If you need to also split on a space, you can add a space between the square brackets.

const str = 'a.b c'; const result = str.split(/[. ]/); // 👇️ ['a', 'b', 'c'] console.log(result);

If you ever need help reading a regular expression, check this regex cheatsheet from MDN out.

Here's an example of a regular expression that splits the string on all special characters.

const str = 'a.b,c-d_e=f\\g/h'; const specialChars = /[`!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?~]/; const result = str.split(specialChars); // 👇️ ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'] console.log(result);

The regular expression we used matches any special character. You could also add a space in the square brackets, if you consider a space to be a special character.

Conversely, you could also remove any of the characters between the brackets, if you don't consider them to be special characters.

Use the search field on my Home Page to filter through my more than 1,000 articles.