How to replace a character within a string with regex?

by dalton_moen , in category: Third Party Scripts , 6 days ago

How to replace a character within a string with regex?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by elisha_langworth , 5 days ago

@dalton_moen 

To replace a character within a string using regex, you can use the String.prototype.replace() method in JavaScript. Here's an example code snippet that replaces all occurrences of a specific character with another character in a string using a regular expression:

1
2
3
4
5
6
7
8
let str = "Hello World!";
let charToReplace = "o";
let replacementChar = "x";

let regex = new RegExp(charToReplace, "g");
let newStr = str.replace(regex, replacementChar);

console.log(newStr); // Output: Hellx Wxrld!


In the above code, we create a regular expression regex to match all occurrences of the character "o" and then use the replace() method to replace those occurrences with the character "x" in the string str. The resulting string newStr would be "Hellx Wxrld!".