pradeep1991singh pradeep1991singh - 7 months ago 39
Javascript Question

How to replace particular text string with other string using regex

How to replace string:

6/9/1985 1234567890 ABC 301 DURGA NIWAS

to convert this in:

6/9/1985 1234567890 301 DURGA NIWAS

Actually I want to replace whitespace between email and string just before email with underscore, string to lowercase.


Note that when you need to modify a string with replace, you can pass captured substrings of text to a callback function where you ca maniplate them further.

So, you need a regex that captures the word before an email:


See a regex demo and a sample code below:

var s = '6/9/1985 1234567890 ABC 301 DURGA NIWAS';
var res = s.replace(/(\S+)\s+([^@\s]+@\S+)/, function (m, grp1, grp2, offset, input) {
  return grp1.toLowerCase() + "_" + grp2;