javascript - 正则表达式:如何替换 html 内容中的大括号,样式标签内的大括号除外?
问题描述
我有一个html内容如下。我想将“ {
”替换为“ {{
” ,将“”替换}
为“ }}
”。但我想在样式标签中保留单个大括号。
注意:我使用的是 javascript,并且我从数据库中读取了 html 内容,因为它存储在 db 中。
<html>
<head>
<style type="text/css" rel="stylesheet" media="all">
p {
font-size: 14px;
}
</style>
</head>
<body>
<p>My name is {name}</p>
<p>My age is {age}</p>
</body>
预期输出如下。
<html>
<head>
<style type="text/css" rel="stylesheet" media="all">
p {
font-size: 14px;
}
</style>
</head>
<body>
<p>My name is {{name}}</p>
<p>My age is {{age}}</p>
</body>
解决方案
试试这个
let str = `<html>
<head>
<style type="text/css" rel="stylesheet" media="all">
p {
font-size: 14px;
}
</style>
</head>
<body>
<p>My name is {name}</p>
<p>My age is {age}</p>
</body>`;
console.log(str.replace(/({|})(?=[^.{1}\s*])/g, "$1$1"));
推荐阅读
- python - 显示 -h 时的 argparse 自定义“可选参数描述”
- node.js - 如何从节点 API 访问私有 Git 存储库中的 JSON 文件
- arrays - 如何在 Angular 中使用平面数组创建树
- python - 尝试在 Heroku 上部署烧瓶应用程序,部署工作正常,直到我在我的代码中添加会话,然后它给出 500 内部错误。如何解决这个问题?
- xaml - 在 StackPanel(或任何 UIElement 而不是后面)上渲染 Win2D 阴影
- c# - 如何使视图对触摸不可见?
- c++ - Hiding C++ symbols with -fvisibility=hidden
- python - 将 Django 项目从 Windows 迁移到 Mac 迁移
- c++ - c++ 指针用作伪数组。将数字分配给没有数组的内存的多个连续位置
- c# - 如何根据单选按钮选择填充复选框文本值