Home >Web Front-end >JS Tutorial >JavaScript `string.replace()` useful cases
Replace the first occurrence of a substring.
let str = "Hello world!"; let result = str.replace("world", "JavaScript"); // Output: "Hello JavaScript!"
Replace all occurrences of a substring, use the global (g) flag with regular expression.
let str = "Hello world, world!"; let result = str.replace(/world/g, "JavaScript"); // Output: "Hello JavaScript, JavaScript!"
You can make the replacement case-insensitive using the i flag.
let str = "Hello World, World!"; let result = str.replace(/world/gi, "JavaScript") // Output: "Hello JavaScript, JavaScript!"
Replace only whole words using \b word boundary.
let str = "This is a test word, test."; let result = str.replace(/\btest\b/, "success"); // Output: "This is a success word, test."
Replace all occurrences of the whole word, use the global flag.
let str = "This is a test word, test."; let result = str.replace(/\btest\b/g, "success"); // Output: "This is a success word, success."
You can pass a function to replace() that dynamically generates the replacement string.
let str = "The price is $10"; let result = str.replace(/\$\d+/g, (match) => { return `$${parseInt(match.substring(1)) * 2}` }); // Output: "The price is $20"
Using regular expressions, you can capture parts of the match and reuse them in the replacement string.
let str = "John Smith"; let result = str.replace(/(\w+)\s(\w+)/, "$2, $1"); // Output: "Smith, John"
If you need to replace special characters like . or *, you need to escape them in the regular expression.
let str = "Price: 5.99"; let result = str.replace(/\./, ","); // Output: "Price: 5,99"
To replace characters that aren't in the ASCII range, you can use Unicode properties.
let str = "Héllo Wörld"; let result = str.replace(/[^\x00-\x7F]/g, ""); // Output: "Hllo Wrld"
You can replace digits (or groups of digits) using regular expressions.
let str = "Contact: 123-456-7890"; let result = str.replace(/\d{3}/g, "***"); // Output: "Contact: ***-***-***0"
You can also use Unicode escape sequences to replace special characters.
let str = "I love ☕!"; let result = str.replace(/\u2615/g, "coffee"); // Output: "I love coffee!"
The above is the detailed content of JavaScript `string.replace()` useful cases. For more information, please follow other related articles on the PHP Chinese website!