1

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.

2 Answers 2

3

@* 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.

/[!%$@]+/
Sign up to request clarification or add additional context in comments.

Comments

2

Use the following:

var splittedArray = toSplit.split(/[!%$@]+/);

Your current code will split between every character because @* will match empty strings. I am assuming since you used @* that you want to consider consecutive characters a single delimiter, which is why the + is at the end of the regex. This will only match one or more characters, so it will not match empty strings.

The [...] syntax is a character class, which is like alternation with the | character except that it only works for single characters, so [!%$@] will match either !, %, $, or @. Inside of the character class the escaping rules change a little bit, so you can just use $ instead of \$.

1 Comment

@T.J.Crowder Added explanation, I usually post the code first and then add details in an edit.

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.