Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Better ways to modify string with multiple methods using JavaScript
JavaScript provides several string methods that can be combined to modify and format strings effectively. You can use methods like toLowerCase(), toUpperCase(), charAt(), and slice() together to achieve proper string formatting.
Let's say we have the following mixed-case string:
var sentence = "tHIS iS tHE JavaScript pROGRAM";
console.log("Original:", sentence);
Original: tHIS iS tHE JavaScript pROGRAM
Method 1: Using charAt() and slice()
This approach capitalizes the first letter and converts the rest to lowercase:
var sentence = "tHIS iS tHE JavaScript pROGRAM";
function modifyStringWithMultipleMethods(sentence) {
return sentence.charAt(0).toUpperCase() + sentence.slice(1).toLowerCase();
}
console.log(modifyStringWithMultipleMethods(sentence));
This is the javascript program
Method 2: Title Case with split() and map()
To capitalize the first letter of each word:
var sentence = "tHIS iS tHE JavaScript pROGRAM";
function toTitleCase(str) {
return str.toLowerCase()
.split(' ')
.map(word => word.charAt(0).toUpperCase() + word.slice(1))
.join(' ');
}
console.log(toTitleCase(sentence));
This Is The Javascript Program
Method 3: Using replace() with Regular Expression
A more advanced approach using regex to capitalize words:
var sentence = "tHIS iS tHE JavaScript pROGRAM";
function capitalizeWords(str) {
return str.toLowerCase().replace(/\b\w/g, char => char.toUpperCase());
}
console.log(capitalizeWords(sentence));
This Is The Javascript Program
Comparison
| Method | Result | Use Case |
|---|---|---|
| charAt() + slice() | Sentence case | Simple capitalization |
| split() + map() | Title case | Capitalize each word |
| replace() + regex | Title case | Advanced pattern matching |
Multiple Transformations
You can chain multiple string methods for complex transformations:
var messyString = " hELLo WoRLD ";
// Chain multiple methods
var cleaned = messyString
.trim() // Remove whitespace
.toLowerCase() // Convert to lowercase
.replace(/\b\w/g, c => c.toUpperCase()); // Capitalize words
console.log("Original: '" + messyString + "'");
console.log("Cleaned: '" + cleaned + "'");
Original: ' hELLo WoRLD ' Cleaned: 'Hello World'
Conclusion
JavaScript string methods can be combined effectively to modify and format strings. Choose charAt() + slice() for simple sentence case, or use split() + map() for title case formatting.
