javascript - 使用 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>"
)。
解决方案
我在做更多研究时学到了一些东西:string.replace
可以将回调函数作为第二个参数。
有了这个,我找到了这个解决方案:
var newCont = content.replace(
/\<([A-Z])([A-Za-z])*( ?\/)?\>/g,
(match) => components[match.replace(/[\<\/\> ]/g, "")] //remove <,/,>, and space characters
);
推荐阅读
- java - 未使用 @RequiredArgsConstuctor 注释注入的最终变量
- matlab - 使用 MATLAB 测量微观粒子的 Feret 直径
- elasticsearch - updateSearchIndexConfig.php
- docker - 容器无法连接到互联网
- javascript - 参数列表后缺少错误 - Selenium Python(执行 Javascript)
- ios - 我是否需要物理 iPhone 来编译和分发 IOS 应用程序?
- c# - 错误:未定义或导入预定义类型“System.Range”
- python - VSCode FileNotFoundError
- haskell - 如何让 GHCi 重新加载包括本地依赖库中的更改?
- java - Spring Boot 应用程序问题