41

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?

majidarif
  • 18,694
  • 16
  • 88
  • 133

3 Answers3

73

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
akirk
  • 6,757
  • 2
  • 34
  • 57
  • oh right, I noticed that too. Why could that be happening? Tried your solution and it works. But is this the only way? anyways, can accept in 7min. – majidarif Apr 02 '14 at 11:11
  • 3
    Well, `.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. – akirk Apr 02 '14 at 11:16
  • 1
    This came as a blessing after 4 hours of head smashing at RnD. It was worth it. :D – TheCleverIdiot Feb 07 '20 at 10:19
18

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;
}
Liam Mitchell
  • 1,001
  • 13
  • 23
0

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.

Abir Taheer
  • 2,502
  • 3
  • 12
  • 34