Martinloc Martinloc - 5 months ago 6
jQuery Question

How to format a string in JS?

I am using an external api.

Some of the entry of the object looks like:


description : "Watch the full 12 minute film: https://vimeo.com/108679594\n\nPresented by Philips TV and Atomic Skis\nFeaturing: Pep Fujas, Eric Hjorleifson, Daron Rahlves, and Chris Benchetler\nMusic: First Aid Kit: 'My Silver Lining'\n\nFrom the depth of the creative visuals to the groundbreaking, never-been-done-before scale of the shoot, Afterglow is being hailed as one of the most cinematically profound ski movies ever made. Deep pillows and Alaskan spines, all filmed at night, with massive lights, custom made LED suits, and a national governments worth of logistics, planning, and civil engineering. \n\nFilmed as a partnership between Sweetgrass Productions, Philips TV, and the Swedish Agency Ahlstrand & Wållgren, it's two parts creativity, one part branded content, and a pinch of masochism for good measure."


I am trying to loop through the above string and replace all the
\n
with break line spaces. I also want to wrap all sentences beginning with http:// or https:// inside an
<a>
tag.

What I got so far:

function formatString(str) {
str.replace(new RegExp('\r?\n','g'), '<br />');
return str;
}


This works fine for replacing the
\n
with
<br>
but not sure how to proceed for the second part (wrapping into
<a>
).

Please note that since there are hundred of entries in the API, and this function has to format a lot of strings.

Answer

You would just tag on another replace regex for converting the links. Mathias Bynens - URL Regex is a great page to base your regular expression on (depending on how complex you want it to be).

function formatString(str) {
    return str.replace(/\r?\n/g, '<br />')
              .replace(/((https?|ftp):\/\/[^\s/$.?#].[^\s\\\<]*)/g, "<a href='$1'>$1</a>");
}
Comments