3

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.

6
  • 1
    This is not a valid code Commented Aug 30, 2014 at 13:26
  • It's not valid at all? No methods to fix this? :/ Commented Aug 30, 2014 at 13:29
  • Royi means that your example code is not valid. Strings may contain newlines (of any kind), but you cannot declare them the way you did. Commented Aug 30, 2014 at 13:33
  • Where are you getting this string from? You write it directly? If yes, you need to add \n\ at the end of each line. Otherwise whatever language returns that string it's simply wrong and will break your JS and (as strangely suggested) no other replace method will work any more cause of broken code (easily visible in console errors). Commented Aug 30, 2014 at 13:33
  • I wanted to input a similar string in a function, so I did't actually need \n or \r. I was wondering if there was a way to legalize this kind of code. Commented Aug 30, 2014 at 13:42

2 Answers 2

21

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, ' ');
Sign up to request clarification or add additional context in comments.

Comments

2

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.