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?

2

1 Answer 1

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));

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.