Pratap M
Pratap M

Reputation: 1081

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?

Upvotes: 1

Views: 464

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626738

You may use

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

See the JS demo:

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

The pattern will match:

  • ([^_]) - Group 1: any char but _
  • (?=[A-Z\d]) - 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.

Upvotes: 1

Related Questions