-2

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 DOC_ID:SECTION_ID with @ 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.

Output:

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>.

Burak Erdem
  • 19,630
  • 7
  • 36
  • 56

1 Answers1

1

I believe the regex you're looking for is

@?(\d+):(\d+)

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.

fstanis
  • 5,234
  • 1
  • 23
  • 42