Javascript - remove '\ n' from a string

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 try to misinform the string by deleting \n, but when I do .replace(/\\\n/g, ''), it doesn't seem to catch it. I also searched Google and found:

.. according to 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 break the backslash, it returns false: (/\\\/g).test(strObj)

RegEx tester fixes \ncorrectly: http://regexr.com/3d3pe

+4
source share
3 answers

It should just be

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

if the string is not actually

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

what will it be

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

RegEx , String#trim, .

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;
+3

You don't need a backslash.

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

+2
source

All Articles