scx
scx

Reputation: 2789

Splitting string with regular expression to make it array without empty element

Here, I have example javascipt string:

example_string = "Answer 1| Answer 2| Answer 3|";

I am trying to get array like this using regular expression:

Array ["Answer 1", " Answer 2", " Answer 3"]

I have tried:

result = example_string.split('/[|]+/g');

and also with the following patterns

'/[|]+/g'
'/[|]+\b/g'
'/[|]+[^$]/g'

And I am still getting an array with empty element at the end of it:

 Array ["Answer 1", " Answer 2", " Answer 3", ""]

That cause me lot of trouble. Does anyone know where I am making mistake in my pattern or how to fix it?

Upvotes: 7

Views: 21859

Answers (2)

Javier Diaz
Javier Diaz

Reputation: 1830

I always liked matching everything I always hated split but:

Regex for splitting: (\|(?!$)) DEMO

Matching instead of splitting:

Regex: (?:([\w\s]+)\|?)

You can even use [^\|]+ To match whatever you have to match BUT |

DEMO

Upvotes: 8

Martin Ender
Martin Ender

Reputation: 44259

There is no mistake. This is absolutely correct behavior (how would split know that this is not a CSV file with the last column having an empty value?). If you know your string always ends in |, you could remove the last one first manually. Or you could just take away the last element of the array if it is empty. However, I can't seem to find a possibility (in JavaScript) to tell the built-in split function to omit empty results.

Upvotes: 3

Related Questions