Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a line break after a full uppercase title in a string

I am currently working on a project where the API spits a description that is formatted like this:

THIS IS A TITLE This is a paragraph. This is another paragraph.

And the outcome I am trying to get is

THIS IS A TITLE

This is a paragraph

This is another paragraph

I have been playing with some regular expressions but struggling to get the desired result, my current attempt is adding a line break at the end of each Uppercase letter/word.

var myString = "THIS IS A TITLE This is a paragraph of random text. This is another paragraph of random text.";
var myStringFormatted = myString.replace(/([A-Z]+)/g, ",$1").replace(/,/g," <br />").split(",");

Is it possible to get the desired result? (jsfiddle example: https://jsfiddle.net/srwwpxh4/1/)

like image 963
Dan Whiteside Avatar asked Mar 10 '23 18:03

Dan Whiteside


1 Answers

You could use a positive lookahead.

It looks for a non word character first, upper case character followed by a lower case character and insert a line feed before.

var r = /\W+(?=[A-Z][a-z])/g,
    s = 'THIS IS A TITLE This is a paraGraph. This is another paragraph.';

console.log(s.replace(r, '$&\n'));
like image 69
Nina Scholz Avatar answered Apr 24 '23 20:04

Nina Scholz