I’m trying to split a string by the following array of characters:
"!", "%", "$", "@"
I thought about using regex, so I developed the following method which I thought would split the string by the characters:
var splitted = string.split(/\!|%|\$|@*/);
However, when I run the following code, the output is split by every character, not what I was hoping for:
var toSplit = "abc%123!def$456@ghi";
var splittedArray = toSplit.split(/\!|%|\$|@*/);
How could I make it so that splittedArray contains the following elements?
"abc", "123", "def", "456", "ghi"
Any help appreciated.
@*matches the empty string and there’s an empty string between any two characters, so the string is split at every single character. Use+instead:Also if you meant the
+to apply to every character and not just@then group them up:Or better yet, use a character class. This lets you omit the backslashes since none of these characters are special inside square brackets.