0

I have just started using JavaScript so this could just be a syntax error that I am overlooking or could be a regex error but the source of the code seemed to be well accepted.

I got my code from this question.

If I pass the String This is a string \n It doesn't replace the \n and outputs to the webpage This is a string \n.

My code follows:

<p id="commandOutput">Click run and it will output here</p>

<script type="text/javascript">

    var exampleSocket = new WebSocket("ws://localhost:8080/ws")

    var update = function(){
        exampleSocket.onmessage = function (event) {
            document.getElementById("commandOutput").innerHTML = event.data.toString().replace(/(?:\r\n|\r|\n)/g, "<br/>");
        }
    };

    window.setTimeout(update);

</script>

My question refers to this line:

 document.getElementById("commandOutput").innerHTML = event.data.toString().replace(/(?:\r\n|\r|\n)/g, "<br/>");
Dylan
  • 305
  • 3
  • 18

1 Answers1

2

As @Pointy mentioned the problem is:

The regular expression operates on the special control characters for carriage return and newline, not on literal \n

As @ChrisG mentioned, to get around this you can:

Use \\n to mask the backslash

Dylan
  • 305
  • 3
  • 18