Laura Wischel Laura Wischel - 1 year ago 96
JSON Question

Remove linebreaks w/o \r\n

I'm currently working on a website and doing some JS stuff. I'm fairly new to this topic, so please excuse if my question is stupid:)

I have a JSON string with some line breaks, however I cannot parse it into an JSON object (because of the line breaks) - so I need to remove them and already tried it using

stringJSON.replace(/(\r\n|\r|\n)+/, '');

However, this doesn't work, when I do an alert on the string the line breaks are still included.

Do you have any suggestions?

Thanks in advance,

Wiwi :)


"key0": "value 0",
"key1": "value 1",
"key2": "value 2"
"key0": "value 0",
"key1": "value 1",
"key2": "value 2"

Answer Source

You should assign the result of the replace to the stringJSON variable if what you really mean to do is to update the stringJSON variable.

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

Replace doesn't change the original string because strings are immutable in Javascript.

Note: The global flag on the regex (g) allows it to match more than once. Without that flag, only the first line break would be replaced.