Exploring Strings
Learn about different strings functions in JavaScript.
How long is a string?
Every string has a length
property that tells us how many characters it
contains. This property is also accessed using the dot notation we used with
the charAt()
method. For example, the following code will tell us how many
characters are in the string 'Hello'
:
console.log('Hello'.length);
We can also assign a string to a variable and then apply the dot notation to the variable:
const myString = "Hello, is it me you're looking for?";console.log(myString.length);
As we can see, this tells us that there are characters in the string that have
been assigned to the myString
variable.
All properties of primitive data types are immutable. This means that they can’t be changed, so it’s impossible to change the length property of a string by reassigning it to another value. We can try, but our efforts will be futile:
console.log(myString.length = 36); // try to change the length property
Although it looks like the length property of the myString
variable has been
changed to ...