Dan Whiteside Dan Whiteside - 28 days ago 5
Javascript Question

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/)

Answer

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'));

Comments