简体   繁体   中英

Regex replace “<X>” brackets

i'm trying to make some code that'll loop over html forum data and replace some brackets.

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

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

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