views:

42

answers:

2

Hi, I just found this regex in JavaScript

var str=input.replace(/\0/g, "\\0");

Can you please explain me what does it mean? What is the meaning of /\0/g and \\0?

+10  A: 

\0 is the null character.

/\0/g is a pattern that will match all instances of the null character.

"\\0" is a string that will be displayed as "\0", since the first backslash acts as an escape character for the second backslash.

So this line of code replaces all instances of the null character (which is normally unreadable, unless you use a hex viewer) in the string input and replaces them with the human-readable string "\0", then stores the result in the string str.

Donut
Is that really true? I don't think "\0" means the null character; I think it just means the character "0" (0x0030). *edit* nope I tried it and this answer is correct.
Pointy
I can get it to work on a string like `var s = '\000';` - http://jsbin.com/ewina4
Kobi
+5  A: 

It replaces null characters (\0 - Unicode 0x0) in the string with a backslash (\)followed by a 0.

var s = "asd0asd\x00asd";
console.log(s);
s = s.replace(/\0/g, "\\0");
console.log(s);

And the output is:

asd0asd�asd
asd0asd\0asd

Amarghosh