node.js 如何从用户控制台输入中删除新行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10538114/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to remove new line from user console input
提问by Eleeist
How can I remove new line from the user input in Node.js?
如何从 Node.js 中的用户输入中删除新行?
The code:
编码:
var net = require("net");
var clientData = null;
var server = net.createServer(function(client) {
client.on("connect", function() {
client.write("Enter something: ");
});
client.on("data", function(data) {
var clientData = data;
if (clientData != null) {
client.write("You entered " + "'" + clientData + "'" + ". Some more text.");
}
});
});
server.listen(4444);
Let's say I type "Test" in the console, then the following is returned:
假设我在控制台中键入“Test”,然后返回以下内容:
You entered 'Test
'. Some more text.
I would like such an output to appear in the single line. How can I do this?
我希望这样的输出出现在单行中。我怎样才能做到这一点?
回答by kevin
You just need to strip trailing new line.
你只需要去掉尾随的新行。
You can cut the last character like this :
您可以像这样剪切最后一个字符:
clientData.slice(0, clientData.length - 1)
Or you can use regular expressions :
或者您可以使用正则表达式:
clientData.replace(/\n$/, '')
回答by alex
In Windows you might have \r\n there. So in the core it is often done like that:
在 Windows 中,您可能有 \r\n 。所以在核心中,它通常是这样完成的:
clientData.replace(/(\n|\r)+$/, '')
BTW, clientData.trim()function might be useful too.
顺便说一句,clientData.trim()函数也可能有用。

