JavaScript provides built-in methods to manipulate and work with strings. These methods allow you to modify, search, split, and format text efficiently.
toUpperCase()
– Converts to Uppercaselet text = "hello world";
console.log(text.toUpperCase()); // "HELLO WORLD"
toLowerCase()
– Converts to Lowercaselet text = "HELLO WORLD";
console.log(text.toLowerCase()); // "hello world"
slice(start, end)
– Extracts a Portionlet str = "JavaScript";
console.log(str.slice(0, 4)); // "Java"
console.log(str.slice(-6)); // "Script"
💡 Negative values start from the end.
substring(start, end)
– Similar to slice()
but No Negative Valueslet str = "JavaScript";
console.log(str.substring(0, 4)); // "Java"
indexOf(value)
– Finds First Occurrencelet sentence = "Learn JavaScript at JavaScript Academy!";
console.log(sentence.indexOf("JavaScript")); // 6
lastIndexOf(value)
– Finds Last Occurrenceconsole.log(sentence.lastIndexOf("JavaScript")); // 21
includes(value)
– Checks if a String Contains a Valueconsole.log(sentence.includes("Academy")); // true
console.log(sentence.includes("Python")); // false
replace(oldValue, newValue)
– Replaces First Occurrencelet phrase = "I love JavaScript!";
console.log(phrase.replace("JavaScript", "Coding")); // "I love Coding!"
replaceAll(oldValue, newValue)
– Replaces All Occurrenceslet text = "apple apple orange";
console.log(text.replaceAll("apple", "banana")); // "banana banana orange"
trim()
– Removes Spaces from Start and Endlet messyText = " Hello World! ";
console.log(messyText.trim()); // "Hello World!"
trimStart()
– Removes Spaces from the Startconsole.log(messyText.trimStart()); // "Hello World! "
trimEnd()
– Removes Spaces from the Endconsole.log(messyText.trimEnd()); // " Hello World!"
substr(start, length)
– Extracts Part of a Stringlet text = "JavaScript";
console.log(text.substr(4, 6)); // "Script"
💡 Deprecated but still works in older browsers.
JavaScript provides a variety of string methods to manipulate and format text efficiently. These methods help in modifying, searching, extracting, and trimming strings, making text handling much easier.
@asadmukhtar