简体   繁体   中英

remove a carriage return or newline from JavaScript array

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.

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM