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
  • 42,981
  • 12
  • 84
  • 132
devZ
  • 606
  • 1
  • 7
  • 23
  • You can refer this link and get detailed answer. https://stackoverflow.com/questions/66049162/replace-character-in-array-of-objects thanks! – shehanpathi May 26 '22 at 12:03
  • No, it didn't solved my problem, because I had to used regex epression – devZ May 26 '22 at 12:14

3 Answers3

5

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, '')));
BTSM
  • 1,585
  • 8
  • 12
  • 26
3

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

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

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
  • 42,981
  • 12
  • 84
  • 132