-4

I have String structure like:

let originalString = "I am a [h:12[x] with [l:3[y] and also with [m[z] which i want to replace."

I want to replace the sequence [h:12[x] with <span class="h">x</span> and [m[z] to <span class="m">z</span>.

The resultant string should look like.

I am a <span class="h">x</span> with <span class="l">y</span> and also with <span class="m">z</span>  which i want to replace.

1 Answers1

3

One option would be to use a regular expression to match [h:12[x]-like substrings, extract the word characters following the first and second [, then replace with span HTML text, with those groups inserted at the appropriate point:

const originalString = "I am a [h:12[x] with [l:3[y] and also with [m[z] which i want to replace.";
const output = originalString.replace(
  /\[(\w+)[^\[]*\[(\w+)\]/g,
  (_, g1, g2) => `<span class="${g1}">${g2}</span>`
);
console.log(output);

The pattern /\[(\w+)[^\[]*\[(\w+)\]/ means:

\[ - match a literal [

(\w+) - capture one or more word characters in a group

[^\[]* - match zero or more non-[ characters

\[ - match a literal [ again

(\w+) - capture one or more word characters in a group again

\] - match a literal ]

CertainPerformance
  • 260,466
  • 31
  • 181
  • 209
  • does not work properly if x,y,z is replaced with any utf8 character. \[(\w+)\] needs to be replaced with \[(.*?)\] – Sajid Zaman Nov 28 '18 at 11:30
  • Your question does not specify what could exist at that place in the string. Note that [negative character classes](https://stackoverflow.com/questions/22444/my-regex-is-matching-too-much-how-do-i-make-it-stop#comment93020571_22457) are more efficient than lazy repetition - eg `[^\[]*` – CertainPerformance Nov 28 '18 at 11:32