Split on Multiple Characters in JavaScript
Jun 13, 2022
To split a string with multiple characters, you should pass a regular expression as an argument to the split()
function.
You can use []
to define a set of characters, as opposed to a single character, to match.
const sentence = 'Hey, check out this example.';
const example = sentence.split(/[\s,]+/);
example; // ["Hey", "check", "out", "this", "example."]
const sample = 'this-is:a_test';
sample.split(/[-:_]/); // [ 'this', 'is', 'a', 'test' ]
More Fundamentals Tutorials
- How to Add 2 Arrays Together in JavaScript
- The String `match()` Function in JavaScript
- Convert a Set to an Array in JavaScript
- What Does Setting the Length of a JavaScript Array Do?
- Get the Last Element in an Array in JavaScript
- Skip an Index in JavaScript Array map()
- Conditionally Add an Object to an Array in JavaScript