1

I want to replace \n which is in array of objects. For now I came across this, but it replaces only string, not an actual '\n' which makes the line break.

var obj = {
  'a': '\nThe fooman poured the drinks.',
  'b': {
    'c': 'Dogs say fook, but what does the fox say?'
  }
}

console.log(JSON.parse(JSON.stringify(obj).replace(/\n/g, '')));

Thanks to everyone

Mr. Polywhirl
  • 35,562
  • 12
  • 75
  • 123
devZ
  • 102
  • 7

3 Answers3

4

You should use \\n in regax.

var obj = {
   'a' : '\nThe fooman poured the drinks.',
   'b' : {
      'c' : 'Dogs say fook, but what does the fox say?'
   }
}

console.log (JSON.parse(JSON.stringify(obj).replace(/\\n/g, '')));
Etsuko Susui
  • 1,256
  • 3
  • 12
  • 21
2

You should add an another backslash (\\) to select the first one

console.log (JSON.parse(JSON.stringify(obj).replace(/\\n/g, '')));
Focus RS
  • 441
  • 4
  • 9
2

You need to escape the escape back-slash to treat it like a literal back-slash.

Regex: /\\n/g

var obj = {
  'a': '\nThe fooman poured the drinks.',
  'b': {
    'c': 'Dogs say fook, but what does the fox say?'
  }
}

console.log(JSON.parse(JSON.stringify(obj).replace(/\\n/g, '')));
Mr. Polywhirl
  • 35,562
  • 12
  • 75
  • 123