0

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?

rlandster
  • 7,294
  • 14
  • 58
  • 96
user3348410
  • 2,733
  • 10
  • 51
  • 85
  • 1
    Duplicate: https://stackoverflow.com/questions/650022/how-do-i-split-a-string-with-multiple-separators-in-javascript – Synthetx Nov 04 '19 at 03:33
  • 1
    Possible duplicate of [How do I split a string with multiple separators in javascript?](https://stackoverflow.com/questions/650022/how-do-i-split-a-string-with-multiple-separators-in-javascript) – Pardeep Nov 04 '19 at 03:35

1 Answers1

7

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));
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320