-4

I have text that contains certain markers, where I want to replace links according to this scheme: ...[DESCRIPTION][URL]... should become ...<a href="URL">DESCRIPTION</a>...

var string = 'Lorem ipsum [dolor][http://example.com/one] sit amet. Lorem ipsum [dolor][http://example.com/two] sit amet. Lorem ipsum dolor [sit amet][http://example.com/three].'

Should become

var string = 'Lorem ipsum <a href="http://example.com/one">dolor</a> sit amet. Lorem ipsum <a href="http://example.com/two">dolor</a> sit amet. Lorem ipsum dolor <a href="http://example.com/three">sit amet</a>.'

How can I use Javascript to achieve this?

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
Tonald Drump
  • 1,227
  • 1
  • 19
  • 32
  • 1
    When you attempted to solve this problem yourself - before asking this question - how far did you get? Where did you get stuck? What went wrong? What error(s) came from those attempts? – David Thomas Jul 19 '20 at 17:02

1 Answers1

0

Use RegEx to replace all the occurances of [text1][text2].

string.replace(/\[(.*?)\]\[(.*?)\]/, '<a href="$2">$1</a>');

(.*?) accounts for any and all letters from the first [ to the last ] within that same range. The g in the end accounts for all occurances in the same string.

Chloe Dev
  • 271
  • 1
  • 8