Member-only story
JavaScript comes packed with great methods for manipulating strings. From finding lengths to extracting parts to replacing values, string methods should be part of every JS developer’s toolkit.
Let’s explore some super useful methods you may not be taking advantage of yet!
Finding Lengths
The fundamental string property is .length — it returns the number of characters:
const message = 'Hello World!';
const length = message.length; // 12
We can even update variables based on length:
let charsLeft = maxLength;
const message = getInput();
charsLeft -= message.length;
Useful for validating!
Accessing Characters
We often need to work with individual characters. Thankfully, strings act like arrays:
const message = 'JavaScript';
// Get first character
const firstChar = message[0]; // 'J'
// Get last character
const lastChar = message[message.length - 1]; // 't'
We can loop through each using subscript notation like any array.