25
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

Alan Moore
  • 73,866
  • 12
  • 100
  • 156
markphd
  • 1,394
  • 1
  • 12
  • 17
  • Is that a typo in your .replace method? Shouldn't that be `/\\n/` not `/\\\n/`? – char Mar 29 '16 at 03:08
  • 2
    You only need one backslash: `/\n+/g`. http://stackoverflow.com/questions/784539/how-do-i-replace-all-line-breaks-in-a-string-with-br-tags – Tacocat Mar 29 '16 at 03:10

3 Answers3

42

Should just be

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

unless the string is actually

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

that it would be

.replace(/\\n/g, '')
epascarello
  • 204,599
  • 20
  • 195
  • 236
21

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;
Tushar
  • 85,780
  • 21
  • 159
  • 179
3

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" }]}"

Mateen Ulhaq
  • 24,552
  • 19
  • 101
  • 135
Matt
  • 5,315
  • 1
  • 30
  • 57