Skip to content
Advertisement

What value does a substring have if it doesn’t exist?


I have a string, msg. I want to check if the third character in the string exists or not.
I’ve tried if (msg.substring(3, 4) == undefined) { ... } but this doesn’t work. What would the substring be equal to if it does not exist?

Advertisement

Answer

The third character of the string exists if the string has three characters, so the check you are looking for is

msg.length >= 3

As to your question about a non-existent substring, you get the empty string, which you can test in a console:

> "dog".substring(8, 13)
''

It’s generally worth a mention that indexing and taking the length of characters is fraught with Unicode-related difficulties, because what JavaScript thinks of as a character is not really a character, but a UTF-16 character code. So watch out for:

> "😬🤔".length
4
> "😬🤔"[1]
'�'
> "😬🤔"[2]
'�'
> [..."😬🤔"][1]
'🤔'

So if you are looking for better characters do:

[...msg].length >= 3

That will still not work with Unicode grapheme clusters, but it is at least better than taking the actual length of string, which is broken in JavaScript (unless you are dealing with what they call BMP characters).

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement