I am getting a dynamic text from DB via an API call in following format
Test 1<br>Test 2<br>Test 3
How can I break this string where there is a 'br' tag and add line breaks? I need to show the string in below format
Test 1
Test 2
Test 3
Can someone please shed some light.
UPDATE: Tried below code, space is being added instead of new line
gridData.STATUSNOTES = gridData.STATUSNOTES.replaceAll('<br>', '\n');
Inserting a newline code \n , \r\n into a string will result in a line break at that location. On Unix, including Mac, \n (LF) is often used, and on Windows, \r\n (CR + LF) is often used as a newline code.
The newline character is \n in JavaScript and many other languages. All you need to do is add \n character whenever you require a line break to add a new line to a string.
You can simply append the text using innerHTML like:
var content = "Test 1<br>Test 2<br>Test 3"
document.getElementById("result").innerHTML = content
<div id="result"></div>
If it doesn't work, in any case like the parent element doesn't permit, you can make use of div
or any element with display
property as block
as block-level element always starts on a new line and always takes up the full width available. Here's an example of converting your string to be placed in new lines:
var content = "Test 1<br>Test 2<br>Test 3"
var result = "";
content.split("<br>").map(element => result += `<div>${element}</div>`)
document.getElementById("result").innerHTML = result
<div id="result"></div>
To do nothing with the HTML but just add a line break in a text, you can replace all br
with \n
const content = 'Test 1<br>Test 2<br>Test 3'.replaceAll('<br>', '\n');
console.log(content);
If you are looking to use \n
as a line break stuff, probably you can use a CSS style white-space: pre-line
. This is a CSS way of breaking lines using \n
. Hope this helps.
var content = "Test 1<br>Test 2<br>Test 3".replaceAll("<br>","\n")
document.getElementById("result").innerHTML = content
<div id="result" style="white-space: pre-line;"></div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With