pradeep1991singh pradeep1991singh - 12 days ago 6
Javascript Question

How to replace particular text string with other string using regex

How to replace string:

6/9/1985 1234567890 ABC test@yahoo.co.in 301 DURGA NIWAS


to convert this in:

6/9/1985 1234567890 abc_test@yahoo.co.in 301 DURGA NIWAS


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

Answer

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:

(\S+)\s+([^@\s]+@\S+)

See a regex demo and a sample code below:

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

Comments