How to replace the string using regex in javascript?

by lindsey.homenick , in category: Javascript , 6 months ago

How to replace the string using regex in javascript?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by cortez.connelly , 6 months ago

@lindsey.homenick 

To replace a string using regex in JavaScript, you can use the replace() method. Here's an example:

1
2
3
4
5
6
7
// Replace a specific string with a new string using regex
var originalString = "Hello, 123 world!";
var regex = /123/;
var newString = originalString.replace(regex, "456");

console.log(newString);
// Output: "Hello, 456 world!"


In this example, the replace() method takes two parameters: the regex pattern /123/ and the new string "456". The method searches for the regex pattern in the original string and replaces it with the new string.


You can also use regex flags, such as i for case-insensitive search, g for global search, etc. For example:

1
2
3
4
5
6
7
// Replace all occurrences of a specific string with a new string using regex
var originalString = "Hello, 123 world! I am 123.";
var regex = /123/g;
var newString = originalString.replace(regex, "456");

console.log(newString);
// Output: "Hello, 456 world! I am 456."


In this updated example, the g flag is used in the regex pattern /123/g to indicate a global search and replace. So all occurrences of "123" in the original string are replaced with "456".