我刚刚开始使用JavaScript,因此这可能只是我忽略的语法错误,或者可能是正则错误,但代码的来源似乎已被很好地接受。
我从这个问题中得到了我的代码。
如果我传递字符串This is a string n
,则不会替换n
并输出到网页This is a string n
。
我的代码如下:
<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(/(?:rn|r|n)/g, "<br/>");
}
};
window.setTimeout(update);
</script>
我的问题是指以下行:
document.getElementById("commandOutput").innerHTML = event.data.toString().replace(/(?:rn|r|n)/g, "<br/>");
@pointy提到的问题是:
正则表达式在运输返回和纽文的特殊控制字符上运行,而不是字面的
n
正如@chrisg所述,要解决这个问题,您可以:
使用
\n
掩盖Backslash