0

I am trying to remove HTML tags from a string, but I want to remove line breaks. The code below doesn't work, and so far, I haven't found a regex solutions that works.

let input = "First<br>Second"
let cleaned = document.createElement("pre");
cleaned.innerHTML = input;
let output = cleaned.innerText;
console.log(output);

What I want: "First\nSecond"

What it returns: "FirstSecond"

How do I fix this?

RobG
  • 142,382
  • 31
  • 172
  • 209
user12976477
  • 57
  • 1
  • 7
  • I guess it depends on which browser you use, in Safari the line break is preserved, but not Firefox, Opera or Chrome. I think this is a throwback to the browser wars, when Microsoft invented innerText and the W3C came up with textContent. They worked a little differently, which has persisted to this day, and Firefox's Mozilla/Netscape roots seems to mean it implements textContent for both. – RobG Apr 22 '20 at 00:28

2 Answers2

0

You say you havent gotten any regex to work, have you tried this?

cleaned.innerHTML = input.replace(/<br>/gi, "\n");
MVB76
  • 149
  • 7
  • [*RegEx match open tags except XHTML self-contained tags*](https://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags) – RobG Apr 22 '20 at 00:29
  • innerHTML does not display but innerText displays in my browser – Russo Jan 30 '23 at 09:36
0

Will this work?

let input = "First<br>Second"
let output = input.replace("<br>", "\\n");
console.log(output);
Jy T
  • 86
  • 8
  • This is close, but the input might have other tags like `

    ` and ``.

    – user12976477 Apr 22 '20 at 06:00
  • I already suggested this, and it works. You said you wanted to remove the
    tag, insert a newline character, and output it to the console. Why are you mentioning other tags? Do you want to handle those also?
    – MVB76 Apr 23 '20 at 00:18
  • 1
    @user12976477, will this work then? `let input = "First
    Second"` then `let output = input.replace(/<\/?[^>]+(>|$)/g, "/n");`
    – Jy T Apr 23 '20 at 00:25
  • @Jy T Yes! That's the first regex that works for me. Thanks. – user12976477 Apr 23 '20 at 07:31