Replace and Split String Content
In this step, you'll learn how to manipulate strings using the replace() and split() methods in JavaScript. These methods are powerful tools for modifying and breaking down string content.
Open the WebIDE and continue working in the ~/project/string-basics.js file. Add the following code to explore string replacement and splitting:
// Original string
let sentence = "Hello, world! Welcome to JavaScript programming.";
// Replace method: replace specific words or characters
let replacedSentence = sentence.replace("world", "JavaScript");
console.log("Replaced sentence:", replacedSentence);
// Global replacement using regular expression
let cleanedSentence = sentence.replace(/[!.]/g, "");
console.log("Cleaned sentence:", cleanedSentence);
// Split method: convert string to an array
let words = sentence.split(" ");
console.log("Words array:", words);
// Split with limit
let limitedWords = sentence.split(" ", 3);
console.log("Limited words:", limitedWords);
// Practical example: parsing CSV-like data
let userData = "John,Doe,30,Developer";
let userDetails = userData.split(",");
console.log("User First Name:", userDetails[0]);
console.log("User Last Name:", userDetails[1]);
When you run this code, you'll see the following output:
Example output:
Replaced sentence: Hello, JavaScript! Welcome to JavaScript programming.
Cleaned sentence: Hello, world Welcome to JavaScript programming
Words array: [ 'Hello,', 'world!', 'Welcome', 'to', 'JavaScript', 'programming.' ]
Limited words: [ 'Hello,', 'world!', 'Welcome' ]
User First Name: John
User Last Name: Doe
Key points about replace() and split():
replace() substitutes part of a string with another string
- Use regular expressions with
replace() for global replacements
split() breaks a string into an array based on a separator
split() can take an optional limit parameter to control the number of splits