简体   繁体   中英

regex: How to replace curly brackets in the html content except the curly brackets inside style tags?

I have a html content as below. I want to replace " { " with " {{ " and " } " with " }} ". But I want to retain the single curly brackets in the style tags.

Note: I'm using javascript and I read the html content from the database since it is stored in 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>

Expected output is as below.

<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>

Try this

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

Maybe this regex will help:

str.replace(/\{(\w+)\}/gm, "{{$1}}")

See this at Regex101

 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(/\\{(\\w+)\\}/gm, "{{$1}}")) 

This regular expression will search for any single alphanumeric string surrounded in curly brackets. The parentheses capture this inner "word". All this is replaced by the captured word surrounded by double curly brackets.

Any opening curly bracket followed by a space or a line break will not match.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM