Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - Remove '\n' from 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 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

like image 825
forloop Avatar asked Mar 29 '16 03:03

forloop


2 Answers

Should just be

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

unless the string is actually

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

that it would be

.replace(/\\n/g, '')
like image 121
epascarello Avatar answered Sep 18 '22 13:09

epascarello


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;
like image 44
Tushar Avatar answered Sep 19 '22 13:09

Tushar