Why doesn't the null-terminator placed arbitrarily in a string terminate it?

0x499602D2 picture 0x499602D2 · Sep 26, 2012 · Viewed 8.7k times · Source

The null character or null-terminator (\0) is to be used to terminate a contiguous sequence of characters. I find that in C, I can add the character into a string at a random position and the string will be cut off from that point. For example:

char * s = "Hello\0World";

will result in s being equal to the string "Hello". In JavaScript, however, this is not the case:

var s = "Hello\0World";

The above won't work as expected. s will be equal to the string "HelloWorld".

Why doesn't this work?

Answer

loganfsmyth picture loganfsmyth · Sep 26, 2012

JavaScript does not use NULL terminated strings, while C does.

Javascript strings are stored by keeping track of the characters and the length separately instead of trying to assume that a NULL marks the end of the string.