-4

I have a string, with a bunch of sentences separated by periods. For example:

const test = 'Dolore nostrud enim ea fugiat amet cupidatat enim. Fugiat qui tempor adipisicing velit et officia aliqua aliqua culpa ad veniam fugiat. Velit voluptate pariatur minim labore occaecat qui velit nostrud non deserunt non est voluptate. Quis est veniam sint nisi do.'

My desired outcome is to be able to turn each sentence of this paragraph into bullet points. I'm not concerned about creating the bullet points, I just need to break up this paragraph into an array of strings.

I'm assuming I need to write an algorithm that splits each sentence by a delimiter (doesn't have to a period but I used one in this example) and push them to a new array. I'm not that good working with regular expressions so I would appreciate any help.

learnerforlife
  • 189
  • 1
  • 3
  • 15
  • 3
    Use `test.split('.')`? Like you said, it doesn't have to be a `.`, so replace that as need be – Kobe Jun 26 '19 at 14:02
  • Depending on the use case you could very easily just use `string.split()`: `'some sentence. another sentence'.split('.')`, which would produce an array: `[''some sentence', ' another sentence']` – Vasil Dininski Jun 26 '19 at 14:03

1 Answers1

4

Using split, we can convert the string into an array where each element in the array is a sentence. Sentences are assumed to be delimited by either a ., !, ? or a ;.

Then, the array can be filtered to remove elements that are empty strings (for example, the last element of the array would be empty if the last character of the initial string was a sentence delimiter). Once filtered, the array can be mapped to HTML and inserted into a <ul> element.

const test = 'Dolore nostrud enim ea fugiat amet cupidatat enim. Fugiat qui tempor adipisicing velit et officia aliqua aliqua culpa ad veniam fugiat. Velit voluptate pariatur minim labore occaecat qui velit nostrud non deserunt non est voluptate. Quis est veniam sint nisi do.'


document.querySelector('ul').innerHTML = test.split(/[\.?!;]/).filter(sentence => sentence).map(sentence => `<li>${sentence}</li>`).join('')
<ul />
Raphael Rafatpanah
  • 19,082
  • 25
  • 92
  • 158