简体   繁体   English

正则表达式替换“<X> ” 括号

[英]Regex replace “<X>” brackets

i'm trying to make some code that'll loop over html forum data and replace some brackets.我正在尝试编写一些代码来遍历 html 论坛数据并替换一些括号。

i'm basically trying to turn我基本上是想转身

<br><br>
<br>
<img src="blah"></img>

to

[br][br]
[br]
[img src="blah"][/img]

and avoid changing text like并避免更改文本,例如

:<
<("<) <(")> (>")>

I'm using javascript and a regex pattern for now.我现在正在使用 javascript 和正则表达式模式。 I was able to find a regex for something between two tags, but not two tags around a string.我能够在两个标签之间找到正则表达式,但不能在字符串周围找到两个标签。 What would be the best way to do this?什么是最好的方法来做到这一点?

There's probably a far more elegant way to do this - but this is basically how I did it in the early 2000's (slight update to more modern JS with const/let etc)可能有一种更优雅的方法来做到这一点 - 但这基本上是我在 2000 年代早期所做的(使用 const/let 等对更现代的 JS 进行轻微更新)

 const input = `<br><br> <br> <img src="blah"></img>`; const body = document.createElement('body'); body.innerHTML = input; function square(obj) { let out = ''; let el; while(el = obj.firstChild) { if (el.nodeType == 3) { out += el.nodeValue; } else { out += `[${el.nodeName}]`; out += square(el); if (!["BR"].includes(el.nodeName)) { out += `[/${el.nodeName}]`; } } el.remove(); } return out; } console.log(square(body));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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