Ceri Westcott
Ceri Westcott

Reputation: 300

Split on separator only and explicitly on that separator

I have a slight issue whereby our API is returning a string that needs to be formatted into a list.

Example string:

"*list1. **subItemOflist. *list2 **subItemOfList2."

which would need to be formatted to:

 - list1
  - subItemOfList
 - list2
  - subItemOfList2

I have created a pipe that would split on '*'. However, the sub-items also contains astericks which are split too.

const mockstring = '*list. **sublist.';
const splitList = mockstring.split('*').splice(1);
console.log(splitList);

produces

[
   "list. ",
   "",
   "sublist."
]

note the empty array nodes.

Upvotes: 1

Views: 87

Answers (1)

Vlad Vidac
Vlad Vidac

Reputation: 998

split takes a regular expression as a parameter so you can use lookaround assertions in it to only match "*" when it's not preceded or followed by another "*": mockstring.split(/(?<!\*)\*(?!\*)/)

If you want to split o an arbitrary amount of "*" (but at least one) then the regular expression is: mockstring.split(/\*+/)

Upvotes: 1

Related Questions