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?
To split a string by a regular expression, pass a regex as a parameter to the split() method, e.g. str. split(/[,. \s]/) . The split method takes a string or regular expression and splits the string based on the provided separator, into an array of substrings.
The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.
split(String regex) method splits this string around matches of the given regular expression. This method works in the same way as invoking the method i.e split(String regex, int limit) with the given expression and a limit argument of zero. Therefore, trailing empty strings are not included in the resulting array.
The split() method splits (divides) a string into two or more substrings depending on a splitter (or divider). The splitter can be a single character, another string, or a regular expression. After splitting the string into multiple substrings, the split() method puts them in an array and returns it.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With