Javascript 将[h:12[x]替换为<;span class=";h>;x<;/span>;

Javascript 将[h:12[x]替换为<;span class=";h>;x<;/span>;,javascript,regex,Javascript,Regex,我有如下字符串结构: let originalString = "I am a [h:12[x] with [l:3[y] and also with [m[z] which i want to replace." 我想用x和[m[z]到z替换序列[h:12[x] 结果字符串应该如下所示 I am a <span class="h">x</span> with <span class="l">y</span> and also with <

我有如下字符串结构:

let originalString = "I am a [h:12[x] with [l:3[y] and also with [m[z] which i want to replace."
我想用
x
和[m[z]到
z
替换序列[h:12[x]

结果字符串应该如下所示

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.
我是一个x加上y和z,我想替换它。

一个选项是使用正则表达式来匹配
[h:12[x]
-类似的子字符串,提取第一个和第二个
[
后面的单词字符,然后替换为
span
HTML文本,并在适当的位置插入这些组:

const originalString=“我是一个[h:12[x]和[l:3[y]以及我要替换的[m[z]。”;
常量输出=originalString.replace(
/\[(\w+)[^\[]*\[(\w+)\]/g,
(u,g1,g2)=>`${g2}`
);

console.log(output);
您尝试了什么?
.replace(“[h:12[x]”,'x')
.@Justinas,如果
x
是其他东西呢?@Oram OP不要求任何其他东西,只要求将此字符串替换为其他字符串string@Justinas
我想用x和[m[z]替换序列[h:12[x]对于z.
他显然要求其他内容。如果用任何utf8字符替换x、y、z,则无法正常工作。[(\w+)]需要替换为[(.*)]您的问题没有指定字符串中该位置可能存在的内容。请注意,这比惰性重复更有效-例如
[^\[]*