0

I am working with an array populated by a text file and parsed with a regex. The first element in my array appears with either \r or \n like so:

" This is the first element"

This only occurs on the first element. How would I go about removing this hidden character? I have tried map with replace('\r', ''), and other iterations of replace with no luck. Thanks for any help.

MJMacarty
  • 537
  • 7
  • 17
  • you would have to escape the backslash. Try `replace('\\r', '')` or even use regex like `replace(/\\r?\\n/g,'')` – jp-jee Sep 11 '14 at 21:44
  • 1
    This looks like you're trying to treat a symptom and not the cause; track down where this char is coming from. – Paul S. Sep 11 '14 at 21:51
  • Replace seems to work fine.. `"\rtest".charCodeAt(0)--=13` `"\rtest".replace('\r','').charCodeAt(0)--=116` – Malk Sep 11 '14 at 21:53

2 Answers2

1

There isn't much more than replace, really. To remove all those characters you can use:

str.replace('\r', '').replace('\n', '');

Mind you have to re-assign the result to the string as it is not an in-place replace but it creates a copy of the string:

str = str.replace('\r', '').replace('\n', '');

I would discourage using a regular expression for such a simple task. It would be overkill and take much more processing time. I admit it's a tiny fraction of time, but in a massive loop it may make a difference.

pid
  • 11,472
  • 6
  • 34
  • 63
0

Tried adding as a comment but a previously answered question should get you going in the right direction.

How to remove all line breaks from a string?

Community
  • 1
  • 1
dooplenty
  • 124
  • 7