Getting the Length of a String

var s = "One Ring"; s.length; //returns 8 var s2 = "To Rule\nThem All"; s2.length; //returns 16 because \n is only 1 character

String objects have a length attribute that contains the number of characters in the string. This includes the number of special characters as well, such as \t and \n. To get the length of the string, simply use the .length attribute on the string object.

Get jQuery and JavaScript Phrasebook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.