19

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 str.replace() 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 str object three times in console output to test it. Here is my result:

hi
user typed: hi
hi
hi

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

Moshe Katz
  • 15,992
  • 7
  • 69
  • 116
lostpebble
  • 328
  • 1
  • 4
  • 8

3 Answers3

58

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.

Moshe Katz
  • 15,992
  • 7
  • 69
  • 116
  • 3
    Wow... such a simple thing to overlook, but caused me so much hassle. Thanks! I'll mark this one correct when I can. – lostpebble Dec 27 '13 at 03:24
2

You were trying to console output the value of str without updating it. You should have done this

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

before console output.

RamenChef
  • 5,557
  • 11
  • 31
  • 43
Milan Kumar
  • 361
  • 1
  • 6
  • 16
-10

you need to convert the data into JSON format. JSON.parse(data) you will remove all new line character and leave the data in JSON format.