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?
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.