简体   繁体   中英

Regex- remove html tags from string except for tags between backticks?

I'm sanitizing content in a JSON response and I'm removing HTML tags using the regex replace below, but I'd like to keep any tags that are between backticks ``

  // remove html tags
    item = item.replace(/<[^>]*>/g, "");

So for example this string:

<p>A `<div>` is a block level element</p>

Would be sanitized to:

A `<div>` is a block level element

If your regex flavor support verbs (*SKIP) & (*FAIL) , you can use:

`<[^>]+>`(*SKIP)(*FAIL)|<[^>]+>

Demo & explanation

If it doesn't, use

  • Find:
`(<[^>]+>`)|<[^>]+>
  • Replace: $1

Demo & explanation

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