我的目的是构建一个解析函数,在字符串(比如博客帖子)中搜索包含在圆括号中唯一标识符周围的任何子字符串,比如(i)。
我目前的实现不起作用。真的很感激你的帮助!
let text = "Hello there (i)Sir(i)";
let italics = /\(i\)(.?*)\(i\)/gi;
let italicsText = text.match(italics);
// text.replace(italics, <i>)发布于 2022-07-13 14:18:28
您可以将replace与regex一起使用,如下所示:
\((.*?)\)/greplace的第二个参数是替换函数。
replace(regexp, replacerFunction):要调用的函数,用于创建用于替换给定regexp或substr的匹配的新子字符串。
How arguments are passed to replacer function
let text = 'Hello there (i)Sir(i)';
let italics = text.replace(/\((.*?)\)/g, (_, match) => `<${match}>`);
console.log(italics);
let text2 = 'Hello there (test)Sir(test)';
let italics2 = text2.replace(/\((.*?)\)/g, (_, match) => `<${match}>`);
console.log(italics2);
发布于 2022-07-13 14:22:59
使用JavaScript "replaceAll“函数:
let text = "Hello there (i)Sir(i)";
console.log(text.replaceAll("(i)", "<i>"));
https://stackoverflow.com/questions/72967685
复制相似问题