Search code examples
javascripthtmltagsnewlineline-breaks

Inserting new lines into innerHTML output


If I were to have a string for a variable be var text = "Hello World!" and I wanted to place a new line after the word Hello, I know I can just create a new variable var b = text.replace(" ", "\n"); and console.log(b) will show the text in 2 lines. (I also know there's multiple ways of doing this without using the replace method).

But I have a bunch of text from a document.getElementById("div").innerHTML that returns a bunch of script and img and more div tags, etc. When it writes this, it doesn't really do any spacing at all and just mushes all together, as many characters in a line as it can.

What would be a way that I can print out the contents of document.getElementById("div").innerHTML such that after the end of each tag </script> </img>, etc., it creates a new line for easier reading? I tried doing replace for (">",">\n") but that didn't do anything which I'm assuming is because of the format that innerHTML is in, not actually a text string I assume.


Solution

  • Alternative to .innerHTML

    .textContext isn't perfect but you can use it fine in this case:

    var text = document.getElementById("div").textContent;
    


    Solution

    Replacing with newlines:

    text.replace(/(img\/|script)\>/ig, '$1>\n')
    


    With breaks:

    text.replace(/(img\/|script)\>/gi, '$1>\<br/>')
    


    RegExp

    (            <- Start capturing group
        img\/    <- Select img\
        |        <- OR
        script   <- Select script
    )
    \>           <- Matches > character
    


    g is the global modifier. i is a case-insensitive modifier. The $1 in the string is replaces the capture group.