Regular expression to insert the underscore in JavaScript

<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.

Leave a Reply

Your email address will not be published. Required fields are marked *