Appearance
JavaScript Strings Tips
1. Use Template Literals
Template literal is preferred over string concatenations for its cleaner and more readable format:
js
const name = "Bob";
const greet = `Hello ${name}`; ✅
const greet2 = 'Hello ' + name; ❌2. includes() to search for string.
js
const str = "Hello, world!";
const hasHello = str.includes("Hello"); // true3. replaceAll() to replace substrings.
js
const str = "This is John. John is cool.";
const newStr = str.replaceAll("John", "Bob"); // This is Bob. Bob is cool.4. split() to split a string into an array.
js
const str = "1,2,3";
const list = str.split(','); // [1,2,3]5. join() to turn an array into string.
js
const list = [1,2,3];
const str = list.join(', '); // "1, 2, 3"6. Use \ to escape special characters.
js
const str = "This is a \"quote\"";
console.log(str) // 'This is a "quote"'7. match() with Regex to find substrings
js
const str = "The cats catches rats";
const matches = str.match(/ats/g); // ["ats", "ats"]8.replace() with Regex to replace parts of the string
js
const str = "A fast cat is a good cat."
str.replace(/cat/g, 'dog') // A fast dog is a good dog9. localeCompare for sorting
js
const str1 = "apple";
const str2 = "banana";
const result = str1.localeCompare(str2); // -1 (str1 is less than str2)
const list = ["banana", "apple"]
list.sort((a, b) => {
return a.localeCompare(b);
}) // ["apple", "banana"]