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?
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
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;
}
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.