How can you remove null bytes from a string in nodejs?
MyString\u0000\u0000\u00000
I tried string.replace('\0', ''); but it doesn't seem to work. Is there any node package that is good for maniputing strings?
It works, but like this it only removes 1 instance of a null-byte. You need to do it with Regular Expressions and the g modifier
var string = 'MyString\u0000\u0000\u0000';
console.log(string.length); // 11
console.log(string.replace('\0', '').length); // 10
console.log(string.replace(/\0/g, '').length); // 8
.trim() is meant to remove whitespace, not control characters. Therefore the way to go is .replace(). If you want trim-like behavior you can use something like string.replace(/^\0+/, '').replace(/\0+$/, ''). This will leave \0 in the middle of the string alone. But I can hardly think of a case where it would make sense.The following replace with a regex will remove the null byte and anything else after it from the string.
string.replace(/\0.*$/g,'');
To trim right of all null (Or any other character just edit the regex) in JavaScript you might want to do something like this.
string.replace(/\0[\s\S]*$/g,'');
So for example:
var a = 'a\0\0test\nnewlinesayswhat!';
console.log(a.replace(/\0[\s\S]*$/g,''));
Outputs 'a'.
after sleeping on it, an index of with substr might be better if your sure null will be in string somewhere.
a.substr(0,a.indexOf('\0'));
Or a function to check if unsure.
function trimNull(a) {
var c = a.indexOf('\0');
if (c>-1) {
return a.substr(0, c);
}
return a;
}
.replace(/\0.*$/, ""). The g flag is redundant; you only match once to cut it off.. in it will remove all characters after the first NUL whatever they might be./\0.*$/, wasn’t supposed to selectively remove multiple NUL sequences; it just trims off everything since the first NUL, including the NUL. It was meant to be a drop-in replacement for /\0.*$/g in this answer.You can also check the character code and use that to filter out null bytes.
function removeNullBytes(str){
return str.split("").filter(char => char.codePointAt(0)).join("")
}
console.log(removeNullBytes("MyString\u0000\u0000\u00000"))
It logs MyString0 because you have an extra 0 placed after your last null byte and you only mentioned wanting to remove null bytes themselves.
The other answers on this post will get rid of everything after the null byte which may or may not be the desired behavior.
.trim()?