27
var strObj = '\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n{"text": true, ["text", "text", "text", "text"], [{ "text", "text" }]}\n\n\n'

I am trying to sanitize a string by stripping out the \n but when I do .replace(/\\\n/g, '') it doesn't seem to catch it. I also Google searched and found:

..in accordance with JavaScript regular expression syntax you need two backslash characters in your regular expression literals such as /\\/ or /\\/g.

But even when I test the expression just to catch backslash, it returns false: (/\\\/g).test(strObj)

RegEx tester captures \n correctly: http://regexr.com/3d3pe

2
  • Is that a typo in your .replace method? Shouldn't that be /\\n/ not /\\\n/? Commented Mar 29, 2016 at 3:08
  • 2
    You only need one backslash: /\n+/g. stackoverflow.com/questions/784539/… Commented Mar 29, 2016 at 3:10

3 Answers 3

52

Should just be

.replace(/\n/g, '')

unless the string is actually

'\\n\\n\\n...

that it would be

.replace(/\\n/g, '')
Sign up to request clarification or add additional context in comments.

Comments

24

No need of using RegEx here, use String#trim to remove leading and trailing spaces.

var strObj = '\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n{"text": true, ["text", "text", "text", "text"], [{ "text", "text" }]}\n\n\n';
var trimmedStr = strObj.trim();

console.log('Before', strObj);
console.log('--------------------------------');
console.log('After', trimmedStr);
document.body.innerHTML = trimmedStr;

1 Comment

This is preferable over the regex answer IMO
4

You don't need the backslashes.

var strObj = '\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n{"text": true, ["text", "text", "text", "text"], [{ "text", "text" }]}\n\n\n';

strObj.replace(/\n/g, '');

This code works as expected.

"{"text": true, ["text", "text", "text", "text"], [{ "text", "text" }]}"

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.