Issue
How can I convert a string (which is actually an ordered list) to an array using JavaScript / TypeScript? Unfortunately, this is what the backend returns.
The string looks like this:
- Lorem Ipsum. 2. Lorem Ipsum. 3. Lorem Ipsum.
I want an array like this:
[
'1. Lorem Ipsum.',
'2. Lorem Ipsum.',
'3. Lorem Ipsum.'
]
..in order to use it like this in my Angular template:
<div>
<ol>
<li *ngFor="let entry of entries">{{entry}}</li>
</ol>
</div>
I already tried it with split()
and JSON.parse()
.. I don’t know what character to use to split the array.
For example console.log (this.entries.split (''));
returns an array with each word of the string. I also tried using other characters to split the string but I can’t find the right one.
Solution
EDIT : Use also positive lookahead to keep the 1. 2. 3.
There might be better regex ( I am very bad at regex )
but this do the trick for this precise exemple, the solution all depend on the regex you apply. but the method to use is split.
var text = "1. Lorem Ipsum. 2. Lorem Ipsum. 3. Lorem Ipsum.";
var regex = new RegExp("(?=[0-9].)");
text.split(regex);
=> OUTPUT
Array(3) [ "1. Lorem Ipsum. ", "2. Lorem Ipsum. ", "3. Lorem Ipsum." ]
Answered By – Crocsx
This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0