user3348410
user3348410

Reputation: 2833

How split multiple characters with javascript

Hello I have a string and I want to split some characters from it like: space, comma and ";". Normally I'm splitting on the comma from such a string:

myText.split(',') 

But I want to split on any of these 3 characters? For example, if the string is "cat dog,fox;cow fish" the result will be the array ["cat", "dog", "fox", "cow", "fish"].

how to do that?

Upvotes: 0

Views: 195

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370699

Use a regular expression instead, with a character set containing [ ,;]:

const str = 'foo bar;baz,buzz'
console.log(str.split(/[ ,;]/));

Or you could .match characters that are not any of those:

const str = 'foo bar;baz,buzz'
console.log(str.match(/[^ ,;]+/g));

Upvotes: 7

Related Questions