首页 > 解决方案 > 使用 RegEx 替换自定义组件

问题描述

我试图创建一个类似于许多 JS 框架的“组件”系统。我是 RegEx 的新手,但我做了一些对我有用的东西:

/\<([A-Z])([A-Za-z])*( ?\/)?\>/g

现在,我尝试在文件中搜索此 RegEx,并将其替换为正确的组件,

var content = "<p>file content</p><Test />";
var components = { Test: "<b>test component</b>" };
content.split(/\<([A-Z])([A-Za-z])*( ?\/)?\>/g).forEach((comp) => {
  newCont = content.replace(
    comp,
    components[comp.substr(1, comp.length - 1)]
  );
});

但它不起作用。
我希望代码删除所有实例<Test />或类似实例,并将它们替换为我对它的定义components(例如更改content"<p>file content</p><b>test component</b>")。

标签: javascriptregex

解决方案


我在做更多研究时学到了一些东西:string.replace可以将回调函数作为第二个参数。
有了这个,我找到了这个解决方案:

var newCont = content.replace(
  /\<([A-Z])([A-Za-z])*( ?\/)?\>/g,
  (match) => components[match.replace(/[\<\/\> ]/g, "")] //remove <,/,>, and space characters
);

推荐阅读