1
<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?

6
  • 2
    Can I just clarify that what you want is all capitalised letters to be prepended with underscore except if the capital letter is the first character? The expected output has prepended underscores for _ssss which is not Capitalised, _y and _ites which again is not capitalised. Commented Aug 14, 2018 at 8:24
  • Try .split(/(?!^)_*([A-Z])/).filter(Boolean).join("_") Commented Aug 14, 2018 at 8:27
  • The input is <div id='x'>ThiIssss_SSSSMySites</div> or ThiIssss_SSSSMySites? Commented Aug 14, 2018 at 8:35
  • @Julio the input is ThiIssss_SSSSMySites Commented Aug 14, 2018 at 8:42
  • I suggest you add more test cases, but my solution should be easy to adapt now. Commented Aug 14, 2018 at 8:54

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

8 Comments

So we split the string into arrays of capital letters starting with(and avoiding the capital letter if it is before and after the capital letter and join them?
@user533 See my explanation above, it does exaclty what I wrote there. Could you please let me know what the expected result is for _MyS_ite?
_M_yS_ite, so if i want for numbers also for example MyS112 so the ans would be M_y_S_1_1_2
@user533 You are adding more examples in comments, please collect them and post in the question. Also, I can't understand why _MyS_ite should result in _M_yS_ite (and not _M_y_S_ite) if MyS112 should result in M_y_S_1_1_2.
@WiktorStribiżew I am assuming that part would be there,as I have not tested that part fully. however, it is just a thing remove \d or not. Let us keep this
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.