JavaScript strings are more than just a way to handle text — they’re a powerful tool with plenty of built-in methods to simplify your coding tasks. Here are 10 must-know tricks to help you harness the full potential of JavaScript strings.
1. Reverse a String in One Line
Reversing a string can be done with a simple combination of methods:
const reverseString = str => str.split('').reverse().join('');
console.log(reverseString("hello")); // Output: "olleh"
2. Check if a String Contains Another String
Using includes
, you can quickly check for substrings:
const contains = str => str.includes("world");
console.log(contains("hello world")); // Output: true
3. Convert a String to Title Case
Capitalize the first letter of each word:
const toTitleCase = str => str.split(' ')
.map(word => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())
.join(' ');
console.log(toTitleCase("javascript string tricks")); // Output: "Javascript String Tricks"