About Lesson
String Functions in JavaScript
JavaScript provides a variety of built-in methods to manipulate strings. Here are some commonly used string functions:
1. length property:
Returns the length of a string.
JavaScript
let text = "Hello, world!";
console.log(text.length); // Output: 13
2. toUpperCase() and toLowerCase():
Converts a string to uppercase or lowercase
JavaScript
let text = "Hello, World!";
console.log(text.toUpperCase()); // Output: "HELLO, WORLD!"
console.log(text.toLowerCase()); // Output: "hello, world!"
3. charAt():
Returns the character at a specified index.
JavaScript
let text = "JavaScript";
console.log(text.charAt(0)); // Output: "J"
4. indexOf() and lastIndexOf():
Finds the index of a substring within a string.
JavaScript
let text = "Hello, world!";
console.log(text.indexOf("world")); // Output: 7
console.log(text.lastIndexOf("o")); // Output: 8
5. slice():
Extracts a part of a string and returns it as a new string.
JavaScript
let text = "JavaScript is fun";
console.log(text.slice(0, 10)); // Output: "JavaScript"
6. substring():
Similar to slice(), but cannot accept negative indexes.
JavaScript
let text = "JavaScript is fun";
console.log(text.substring(0, 10)); // Output: "JavaScript"
7. replace():
Replaces a substring with a new substring.
JavaScript
let text = "Hello, world!";
console.log(text.replace("world", "JavaScript")); // Output: "Hello, JavaScript!"
8. split():
Splits a string into an array based on a delimiter.
JavaScript
let text = "apple,banana,orange";
console.log(text.split(",")); // Output: ["apple", "banana", "orange"]
9. trim():
Removes whitespace from both ends of a string.
JavaScript
let text = " Hello, world! ";
console.log(text.trim()); // Output: "Hello, world!"
10. includes():
Checks if a string contains a certain substring.
JavaScript
let text = "Hello, JavaScript!";
console.log(text.includes("JavaScript")); // Output: true