Javascript: Count the length of a string (like strlen() in PHP!)
07/15/2019 (1106x read)
Javascript can be used to quickly count the length of a string: This works similar to the strlen() function in PHP. So you know if a string contains 2, 3 or 255 characters.
var string = 'this is a string'; var strlength = string.length;
The function to determine the length of a string with Javascript is called „length“: To determine the length of the string, simply append the function to the string variable. The variable „strlength“ in the example above then contains the value 16.
You can easily output this with the alert() function:
alert('The string: "'+string+'" is '+strlength+' characters long!');
This would prompt you with this output:
The string: "this is a string" is 16 characters long!
Please note that, as with strlen() in PHP, not only the letters and numbers are counted. Also relevant for the string length are blanks and special characters: All of them are also counted for the string length. A special feature, however, are control characters. The character „\n“ stands for „new line“: This character is counted as one character by the function strlen(), not as two characters!