How to use the replace method in JavaScript?

The replace method is used to replace a specified substring in a string and return a new string. It takes two parameters, the first one being the substring or regular expression to be replaced, and the second one being the new string or a function used for replacement.

For example, the replace method can be used to replace all spaces in a string with underscores.

let str = "Hello World";
let newStr = str.replace(/ /g, "_");
console.log(newStr); // 输出 "Hello_World"

You can also use the replace method to replace a substring with another string in a string.

let str = "I love coding";
let newStr = str.replace("coding", "programming");
console.log(newStr); // 输出 "I love programming"

Alternatively, you can use a function as the second parameter to dynamically replace the matched substrings.

let str = "123abc456def";
let newStr = str.replace(/[a-z]+/g, function(match) {
  return match.toUpperCase();
});
console.log(newStr); // 输出 "123ABC456DEF"
Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds