JavaScript provides a variety of built-in string methods to perform common operations on strings, such as searching, modifying, and formatting text.
This tutorial covers the most commonly used JavaScript string methods with detailed explanations and code examples.
1. length Property
The length property returns the number of characters in a string.
Example 1: Using length
const text = 'JavaScript is awesome!'; console.log(text.length); // Output: 22
Explanation: This property returns the total number of characters, including spaces and punctuation.
2. toUpperCase() and toLowerCase()
toUpperCase(): Converts all characters in the string to uppercase.
toLowerCase(): Converts all characters in the string to lowercase.
Example 2: Using toUpperCase() and toLowerCase()
const text = 'JavaScript is Fun!'; console.log(text.toUpperCase()); // Output: JAVASCRIPT IS FUN! console.log(text.toLowerCase()); // Output: javascript is fun!
3. indexOf() and lastIndexOf()
indexOf(): Returns the position of the first occurrence of a specified value. If the value is not found, it returns -1.
lastIndexOf(): Returns the position of the last occurrence of a specified value.
Example 3: Using indexOf() and lastIndexOf()
const text = 'Hello, World! Hello, JavaScript!'; console.log(text.indexOf('Hello')); // Output: 0 console.log(text.lastIndexOf('Hello')); // Output: 14 console.log(text.indexOf('Python')); // Output: -1 (not found)
4. includes()
The includes() method checks if a string contains a specified value. It returns true if the value is found; otherwise, it returns false.
Example 4: Using includes()
const text = 'JavaScript is fun!'; console.log(text.includes('JavaScript')); // Output: true console.log(text.includes('Python')); // Output: false
5. startsWith() and endsWith()
startsWith(): Checks if a string starts with a specified value.
endsWith(): Checks if a string ends with a specified value.
Example 5: Using startsWith() and endsWith()
const text = 'JavaScript is awesome!'; console.log(text.startsWith('JavaScript')); // Output: true console.log(text.startsWith('awesome')); // Output: false console.log(text.endsWith('awesome!')); // Output: true console.log(text.endsWith('JavaScript')); // Output: false
6. slice()
The slice() method extracts a section of a string and returns it as a new string. It takes two parameters: the start index (inclusive) and the end index (exclusive).
Example 6: Using slice()
const text = 'Hello, JavaScript!'; console.log(text.slice(0, 5)); // Output: Hello console.log(text.slice(7)); // Output: JavaScript! console.log(text.slice(-10, -1)); // Output: JavaScript
Explanation: Negative indices count from the end of the string.
7. substring()
The substring() method extracts characters from a string, between two specified indices, and returns the new substring. It is similar to slice() but does not support negative indices.
Example 7: Using substring()
const text = 'JavaScript is fun!'; console.log(text.substring(0, 10)); // Output: JavaScript console.log(text.substring(11)); // Output: is fun!
8. substr()
The substr() method extracts a specified number of characters from a string, starting at a given index.
Example 8: Using substr()
const text = 'JavaScript is awesome!'; console.log(text.substr(0, 10)); // Output: JavaScript console.log(text.substr(11, 2)); // Output: is console.log(text.substr(-9, 7)); // Output: awesome
Explanation: The first parameter specifies the starting index, and the second parameter specifies the number of characters to extract.
9. replace() and replaceAll()
replace(): Replaces the first occurrence of a specified value in a string.
replaceAll(): Replaces all occurrences of a specified value in a string.
Example 9: Using replace() and replaceAll()
const text = 'I love JavaScript. JavaScript is awesome!'; console.log(text.replace('JavaScript', 'Python')); // Output: I love Python. JavaScript is awesome! console.log(text.replaceAll('JavaScript', 'Python')); // Output: I love Python. Python is awesome!
Explanation: Use a regular expression with the g flag in replace() to replace all occurrences.
console.log(text.replace(/JavaScript/g, 'Python')); // Output: I love Python. Python is awesome!
10. split()
The split() method splits a string into an array of substrings based on a specified delimiter.
Example 10: Using split()
const text = 'JavaScript,Python,Ruby'; const languages = text.split(','); console.log(languages); // Output: ['JavaScript', 'Python', 'Ruby']
Explanation: You can use any delimiter to split the string, including spaces, commas, or even regular expressions.
11. trim(), trimStart(), and trimEnd()
trim(): Removes whitespace from both ends of a string.
trimStart(): Removes whitespace from the beginning of a string.
trimEnd(): Removes whitespace from the end of a string.
Example 11: Using trim(), trimStart(), and trimEnd()
const text = ' Hello, JavaScript! '; console.log(text.trim()); // Output: 'Hello, JavaScript!' console.log(text.trimStart()); // Output: 'Hello, JavaScript! ' console.log(text.trimEnd()); // Output: ' Hello, JavaScript!'
12. charAt() and charCodeAt()
charAt(): Returns the character at a specified index.
charCodeAt(): Returns the Unicode value of the character at a specified index.
Example 12: Using charAt() and charCodeAt()
const text = 'JavaScript'; console.log(text.charAt(4)); // Output: S console.log(text.charCodeAt(4)); // Output: 83 (Unicode value of 'S')
13. concat()
The concat() method concatenates two or more strings.
Example 13: Using concat()
const str1 = 'Hello, '; const str2 = 'World!'; console.log(str1.concat(str2)); // Output: Hello, World!
Explanation: While you can use the + operator for string concatenation, concat() is another way to join strings.
14. repeat()
The repeat() method returns a new string with a specified number of copies of the original string.
Example 14: Using repeat()
const text = 'Hi! '; console.log(text.repeat(3)); // Output: Hi! Hi! Hi!
15. padStart() and padEnd()
padStart(): Pads the beginning of a string with another string until the resulting string reaches the specified length.
padEnd(): Pads the end of a string with another string until the resulting string reaches the specified length.
Example 15: Using padStart() and padEnd()
const text = '5'; console.log(text.padStart(3, '0')); // Output: '005' console.log(text.padEnd(3, '0')); // Output: '500'
Explanation: These methods are useful for formatting strings, like displaying numbers with leading zeros.
Conclusion
JavaScript provides a rich set of string methods for manipulating and formatting text.
From simple case conversions (toUpperCase() and toLowerCase()) to more complex operations like searching (indexOf(), includes()), extracting (slice(), substring()), and modifying strings (replace(), split()), these methods allow you to work with textual data effectively.
Feel free to experiment with these examples and explore how JavaScript string methods can enhance your applications!