Performing Operations on Strings

JavaScript provides several properties and methods to perform operations on string values. Technically, only objects can have properties and methods. But in JavaScript primitive data types can act like objects when you refer to them with the property access notation (i.e. dot notation).

JavaScript making it possible by creating a temporary wrapper object for primitive data types. This process is done automatically by the JavaScript interpreter in the background.

Getting the Length of a String

The length property returns the length of the string, which is the number of characters contained in the string. This includes the number of special characters as well, such as \t or \n.

var str1 = "This is a paragraph of text.";
document.write(str1.length); // Prints 28
 
var str2 = "This is a \n paragraph of text.";
document.write(str2.length); // Prints 30, because \n is only one character

Note: Since length is a property, not a function, so don’t use parentheses after it like str.length(). Instead just write str.length, otherwise it will produce an error.