Apebble Apebble - 4 months ago 9x
Javascript Question

Remove new line characters from data recieved from node event process.stdin.on("data")

I've been looking for an answer to this, but whatever method I use it just doesn't seem to cut off the new line character at the end of my string.

Here is my code, I've attempted to use

to get rid of the new line characters as it seems to be the standard answer for this problem:

process.stdin.on("data", function(data) {
var str;
str = data.toString();
str.replace(/\r?\n|\r/g, " ");
return console.log("user typed: " + str + str + str);

I've repeated the
object three times in console output to test it. Here is my result:

user typed: hi

As you can see, there are still new line characters being read between each
. I've tried a few other parameters in
but nothing seems to work in getting rid of the new line characters.


You are calling string.replace without assigning the output anywhere. The function does not modify the original string - it creates a new one - but you are not storing the returned value.

Try this:

str = str.replace(/\r?\n|\r/g, " ");

However, if you actually want to remove all whitespace from around the input (not just newline characters at the end), you should use trim:

str = str.trim();

It will likely be more efficient since it is already implemented in the Node.js binary.