Get a string's length with Javascript

Posted in Javascript -

This is one of those posts that looks at a really basic function: how to get the length of a string with Javascript. Yes this is a really basic function, but I found myself reaching for my O'Reilly Javascript book the other day because I couldn't remember if it really was as simple as String.length... In writing this post I know I will never forget it again!

Example:

The following example shows in an alert dialog the length of the string "this is a test":

var mystring = "this is a test";
alert( mystring.length );

And here's the above as a working example:

It's also possible to do this -> "this is a test".length <- which is what the example button above is doing in the onclick event handler.

Apologies to my regular readers for such a basic post, but sometimes I need to write these simple posts so I will always remember a particular function in the future.



Related posts:


Comments