如何在Javascript中的字符串中搜索[SM_g]randomword[SM_h].的所有实例,并将其全部替换为[SM_g]randomword.[SM_h]

我也想用逗号来做。例如-我需要能够将[SM_g]randomword[SM_h],转换为[SM_g]randomword,[SM_h]

到目前为止,这是我的代码:

const periodRegex = /\[SM_g](.*?)\[SM_h](?:[.])/g;
string_afterregex - string_initial.replace(periodRegex, /*I don't know what goes in here*/)

最佳答案

捕获模式,然后使用反向引用重新排序:



const periodRegex = /(\[SM_g].*?)(\[SM_h])([.,])/g;

var string_initial = '[SM_g]randomword[SM_h].'
var string_afterregex = string_initial.replace(periodRegex, "$1$3$2");
console.log(string_afterregex);

var string_initial = '[SM_g]randomword[SM_h],'
console.log(string_initial.replace(periodRegex, "$1$3$2"))

09-29 21:57