In Javascript, you can find the length of a string using the built-in length
property of the string object.
The length
property returns the number of characters in a string, including spaces, punctuation marks, and special characters.
For example:
const str = "Hello, world!";
const len = str.length;
console.log(len); // Output: 13
In this example, the str
variable holds the string “Hello, world!” and the length
property is used to find the length of the string, which is 13. The len
variable stores the length of the string, and it can be used in further calculations or operations.
It’s important to note that the length
property is a property, not a method, so you don’t need to invoke it with parentheses like you would with a function or method.
Also, keep in mind that the length
property is case-sensitive, so it counts both uppercase and lowercase characters as separate characters.
For example:
const str = "JavaScript";
console.log(str.length); // Output: 10
const str2 = "JavaScript is fun!";
console.log(str2.length); // Output: 18
In the first example, the str
variable holds the string “JavaScript”, which has a length of 10 characters. In the second example, the str2
variable holds the string “JavaScript is fun!”, which has a length of 18 characters, including spaces and punctuation marks.
It’s also important to note that the length
property only counts the actual characters in the string, not any HTML tags, if present.
For example:
const htmlString = "<p>Hello, world!</p>";
console.log(htmlString.length); // Output: 20
In this example, the htmlString
variable holds an HTML string "<p>Hello, world!</p>"
, but the length
property only counts the actual characters in the string, not the HTML tags. So the length of htmlString
is 20, not 14.
In conclusion, to find the length of a string in JavaScript, you can use the length
property of the string object, which returns the number of characters in the string.
Thank you for reading, and let’s have conversation with each other
Thank you for reading my article. Let’s have conversation on Twitter and LinkedIn by connecting.