I have the following array
const re = ' ';
var arr = ['\t', '\n3\t3', '\n\t', '\n3\t3', '\n2\t', '\n\t2', '\n']
i need to trim the \t and \n characters from strings. So when i try
for(let i = 0;i < arr.length;i++) {
let row = arr[i].split(re);
console.log(row);
}
i get
['', '']
['\n3', '3']
['\n', '']
['\n3', '3']
['\n2', '']
['\n', '2']
['\n']
i can't find a way to remove the \n charactes here when i get to this point so
when i have just \n as element then it should be replaced with '' - empty string.
If the character includes other things inside for example
\n2
so \n before or after a number then i shold get just the number and to have just 2 inside
How can i replace this \n cahracters
Use replace() function of string combined with map() function of array. It will look like this
arr.map(c => c.replace(/(\n|\t)/gi, ''))
Output will be:
[ '', '33', '', '33', '2', '2', '' ]
If you don't want to see empty strings in array you can just filter them with .filter(Boolean)
arr.map(c => c.replace(/(\n|\t)/gi, '')).filter(Boolean)
Output will be:
[ '33', '33', '2', '2' ]
Reference: Here
It is not good practice to do with split method. You can use replace method instead.
Here is example what you want to do:
var someText = "Here's some text.\n It has some line breaks that will be removed \r using Javascript.\r\n";
someText = someText.replace(/(\r\n|\n|\r)/gm,"");
console.log(someText);
You can edit your replace method what you want to use in it.
Note: "/(\r\n|\n|\r)/gm" this is a regex.
You may do a regex replacement on [\t\n]+ to remove these characters:
var arr = ['\t', '\n3\t3', '\n\t', '\n3\t3', '\n2\t', '\n\t2', '\n'];
var output = arr.map(x => x.replace(/[\t\n]+/g, ""));
console.log(output);
Note that if there could be other whitespace characters which you also want to remove, just do a regex replacement on \s+.