简体   繁体   English

replace()未能按预期运行,试图替换JavaScript中的换行符(/ n / rn / r)

[英]replace() not functioning as expected attempting to replace newline characters (/n /rn /r) in JavaScript

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. 我刚刚开始使用JavaScript,所以这可能只是我忽略的语法错误,也可能是正则表达式错误,但是代码的来源似乎已为人们所接受。

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 . 如果我传递字符串, This is a string \\n它不会替换\\n并输出到网页。 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/>");

As @Pointy mentioned the problem is: 正如@Pointy提到的那样,问题是:

The regular expression operates on the special control characters for carriage return and newline, not on literal \\n 正则表达式对回车符和换行符的特殊控制字符进行操作,而不对文字\\n

As @ChrisG mentioned, to get around this you can: 如@ChrisG所述,要解决此问题,您可以:

Use \\\\n to mask the backslash 使用\\\\n掩盖反斜杠

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM