Regular expression to insert the underscore in JavaScript Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Regular expression to insert the underscore in JavaScript without wasting too much if your time.

The question is published on by Tutorial Guruji team.

<div id='x'>ThiIssss_SSSSMySites</div>
$('#x').text( $('#x').text().replace(/(?<=[a-zA-Z])(?=[A-Z])/, '_'))

The output expected is:

Thi_Issss_S_S_S_S_My_Sites

Basically first letter even if it is capital it should not be prepended with underscore. Rest all places wherever capital letter is found if it is not prepended with underscore then prepend, I tried lot of ways. Can we achieve this with regular expressions? Or should we need function to do this?

Answer

You may use

s.replace(/([^_])(?=[A-Zd])/g, "$1_")

See the JS demo:

var ss = ["ThiIssss_SSSSMySites", "ThisIsM_M_ySites"];
for (var s of ss) {
   console.log(s, "=>", s.replace(/([^_])(?=[A-Zd])/g, "$1_"));
  }

The pattern will match:

  • ([^_]) – Group 1: any char but _
  • (?=[A-Zd]) – that is followed with an uppercase letter or digit.

The replacement is $1_, the backreference to the value stored in Group 1 and a _ char.

See the regex demo.

We are here to answer your question about Regular expression to insert the underscore in JavaScript - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji