首页 > 解决方案 > 正则表达式:如何替换 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>

标签: javascriptregex

解决方案


试试这个

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"));


推荐阅读