Q:

Replace [h:12[x] with x

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.

A:

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 ]

