-2

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?

1 Answers1

1

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));
Jaromanda X
  • 53,868
  • 5
  • 73
  • 87