String methods
Previously we covered strings like "Hello world"
. In JavaScript, strings are also a special kind of object, and so have properties and methods you can call on them. For example "Hello".length
is 5, as the string has 5 characters.
You may have noticed that arrays are also a special kind of object in JavaScript. In fact in JavaScript pretty much everything is an object! Here are some useful string methods that you can try out in the console.
// Try entering in to the browser console:
// toLowerCase() returns a new string with lower case
"Hello World".toLowerCase() // "hello world"
// toUpperCase() returns a new string with upper case
"Hello World".toUpperCase(); // "HELLO WORLD"
// includes() returns a boolean indicating if a given
// string appears in the string it is called on
"Hello world".includes("world") // true
"Hello world".includes("pizza") // false
// startsWith() returns a boolean indicating if the
// string it is called on starts with a given string
"Hello world".startsWith("Hello") // true
"Hello world".startsWith("Pizza") // false
// endsWith() does the same but for the end of the string
"Hello world".endsWith("world") // true
"Hello world".endsWith("pizza") // false
// repeat() returns a new string which repeats the
// string it is called on a number of times
"😀".repeat(5) // 😀😀😀😀😀
// split() returns an array of strings separated
// by a given character
"pizza,chocolate,burrito".split(",")
// returns an array:
// ["pizza", "chocolate", "burrito"]
Strings can also be converted to an array with one character per element using the spread operator ...
. The below example shows how the array can then be used to access the number of characters and a character at a specific index.
// A string with an emoji
let str = "Hi😀";
// Convert the string to an array
let arr = [...str];
// The array now has:
// [ "H", "i", "😀" ]
// Log details about the string from the array
console.log(`The array length is ${arr.length}`);
console.log(`The 3rd character is ${arr[2]}`);
You can also use a for-of loop to iterate the characters of the string directly.
// A string with an emoji
let str = "Hi😀";
// Use a for-of loop to repeat for each character
for (let ch of str)
{
console.log(`String character: ${ch}`);
}
There's lots more you can do with strings in JavaScript. See the String MDN documentation for more.