Burak Erdem Burak Erdem - 1 year ago 115
Javascript Question

Parsing special markup with Javascript

I have a text containing some special markup. A colon is separating two integers to indicate that this will be a link to a special page/file/document.

Its syntax is

sign optional in-front.

How can I replace this special markup with a regular HTML link, removing the
sign if there are any?

Original text:

Lorem ipsum @2:6 dolor sit amet, consectetur adipiscing 5:22 fermentum ex. @99:12 Mauris euismod lacus ut lacus maximus laoreet 44:9.


Lorem ipsum <a href="/document/2/section/6">2:6</a> dolor sit amet, consectetur adipiscing <a href="/document/5/section/22">5:22</a> fermentum ex. <a href="/document/99/section/12">99:12</a> Mauris euismod lacus ut lacus maximus laoreet <a href="/document/44/section/9">44:9</a>.

Answer Source

I believe the regex you're looking for is


You would use it this way:

var newStr = str.replace(/@?(\d+):(\d+)/g, '<a href="/document/$1/section/$2">$1:$2</a>');

Would highly recommend you get acquainted with regular expressions and the replace function for further reference.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download