Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove new line in javascript code in string

I have a string with a line-break in the source code of a javascript file, as in:

var str = 'new
           line';

Now I want to delete that line-break in the code. I couldn't find anything on this, I kept getting stuff about \n and \r.

Thanks in advance!

EDIT (2021)

This question was asked a long, long time ago, and it's still being viewed relatively often, so let me elaborate on what I was trying to do and why this question is inherently flawed.

What I was trying to accomplish is simply to use syntax like the above (i.e. multi-line strings) and how I could accomplish that, as the above raises a SyntaxError.

However, the code above is just invalid JS. You cannot use code to fix a syntax error, you just can't make syntax errors in valid usable code.

The above can now be accomplished if we use backticks instead of single quotes to turn the string into a template literal:

var str = `new
           line`;

is totaly valid and would be identical to

var str = 'new\n           line';

As far as removing the newlines goes, I think the answers below address that issue adequately.


2 Answers

If you do not know in advance whether the "new line" is \r or \n (in any combination), easiest is to remove both of them:

str = str.replace(/[\n\r]/g, '');

It does what you ask; you end up with newline. If you want to replace the new line characters with a single space, use

str = str.replace(/[\n\r]+/g, ' ');
like image 168
Jongware Avatar answered Sep 25 '26 01:09

Jongware


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

Replaces all instances of \n or \r in a string with an empty string.

like image 43
ShaneQful Avatar answered Sep 25 '26 03:09

ShaneQful