Find any consecutive lowercase or uppercase letter and include one more

I have a task in Javascript that I need help with. The goal is to insert a special character between a lowercase and uppercase letter when they are matched together.

For example:

  • myHouse => my_House
  • aRandomString => a_Random_String

And so on...

To achieve this, I came up with the following regex pattern:

/([a-z][A-Z](.{0}))+/g

The issue I'm facing is if I use the replace method like this:

"aRandomString".replace(/([a-z][A-Z](.{0}))+/g, '_')

It will result in: _ando_tring

However, I found a solution which involves multiple steps. Is there a simpler way to accomplish this?

var mString = "aRandomString";
var match = mString.match(/([a-z][A-Z](.{0}))+/g, '_')
var save = [...match]
match = match.map(e => [e.slice(0, 1), '_', e.slice(1)].join(''))
save.forEach((s,i) => mString = mString.replace(s, match[i]))
console.log(mString)

Answer №1

A solution is to identify and replace just the lowercase, uppercase pattern you desire with a replacer.

const myString = "aTestStringForMULTIPLEUpperCase";
const updatedString = myString.replace(/[a-z][A-Z]/g, match => `${match[0]}_${match[1]}`);
console.log(updatedString);

Answer №2

For a more inclusive and versatile approach, take into account uppercase boundaries in addition to the traditional lower followed by upper scenario. This method also considers an uppercase letter between two other uppercase letters on one side and a lowercase letter on the other side.

const regXUppecaseBoundaries = (/(?:(?<=[a-z])[A-Z])|(?:(?<=[A-Z])[A-Z](?=[a-z]))/g);

const sampleText = `myHouse aRandomString
aRandomString aTestStringForMULTIPLEUpperCase
myHouse AaAAaTestStringForMULTIPLEUpperCase`;

// Check out the regex101 link for more details: [https://regex101.com/r/OpmSbx/1]
console.log(
  sampleText.replace(regXUppecaseBoundaries, '_$&')
);
.as-console-wrapper { min-height: 100%!important; top: 0; }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Update the CAPTCHA, while also refreshing the entire registration form

JavaScript Snippet <script language="javascript" type="text/javascript"> function updateCaptcha() { $("#captchaimage").attr('src','new_captcha_image.php'); } </script> New Image Code <img src="new_ ...

ng-class in AngularJS not interacting with Scope method

I am in the process of creating a new application. Here is how my index.html file looks: <html ng-app='myApp'> <body ng-controller='mainController'> <div ng-view> </div> </body> </html> My m ...

Is the JavaScript file not being stored in the cache?

As I work on optimizing my web application, I am facing a challenge with a javascript file size of approximately 450K even after compressing it. While I intend to redo the javascripting in due time, for now, I need to go live with what I have. Initially, I ...

Element remains hidden until the developer console is activated

On my website, I've noticed that certain LayerSlider elements are remaining invisible until: The window is resized I disable the Bookmarks bar in Chrome (quite strange, right?) I switch on the Chrome debugger tools This issue is not exclusive to Ch ...

Is it possible for XSS attacks to exploit the HREF attribute when used with jQuery?

Burp suite displaying an error message. The application seems to have a potential vulnerability related to DOM-based cross-site scripting. Data is retrieved from the location and passed to jQuery() using the following statement: jQuery(location). ...

The function .load callback was triggered on five separate occasions

I'm currently working with the code below and I have a feeling that I'm overlooking something important but just can't seem to figure it out. Basically, when the user clicks a button, a fragment of the page is loaded. Once this loading is s ...

Angular 7 error: Form control with name property does not have a valid value accessor

Currently, I am utilizing angular 7 and have a parent and child component set up as demonstrated in the Stackblitz link provided below. Strangely enough, when I assign the formControlName from the child component using "id", everything functions flawlessly ...

What is the best way to trigger a controller action when the datepicker's value changes?

Hello, I have a custom datepicker and I am trying to perform a calculation when the year is changed. The code provided below does not seem to work on onchange. I also attempted using the onchange attribute and calling a JavaScript function like this oncha ...

Angular template not refreshing automatically

Within my controller: $scope.deleteUser = function(user){ $.ajax({ url: "/users/" + user.id.toString(), method: "DELETE", success: function(result){ $scope.users = result["users"]; ...

Detach attention from TextField select component in Material UI and React through manual means

When I create a select input using the TextField component from Material-UI library, I need to manually remove focus after an option is selected. I attempted to achieve this by using a reference to the TextField with the 'inputRef' prop. However, ...

Manage the lineup of tasks in the bull queue by organizing them into groups

I am currently working on a nodejs application that handles queues using the bull library. The application is required to make multiple asynchronous HTTP requests and then process the results of these calls. I'm curious about whether bull would be an ...

Hide all elements in jQuery that do not have a class assigned

I've implemented a straightforward jQuery script that toggles the "active" class on an li element when it is clicked: $('li').click(function() { $(this).toggleClass('active'); }); My goal is to hide all other li elements in t ...

"Encountering a Prisma type error while attempting to add a new record

I am currently utilizing Prisma with a MySQL database. Whenever I attempt to create a new record (School), an error of type pops up in the console. Additionally, I am implementing a framework called Remix.run, although it does not seem to be causing the is ...

Expand and enhance your content with the Vue Sidebar Menu plugin

Recently, I integrated a side-bar-menu utilizing . My goal is to have a sidebar menu that pushes its content when it expands. Any suggestions on which props or styles I should incorporate to achieve this effect? Below is my Vue code: <template> ...

Angular Checkbox Single Select

I have a piece of HTML code with ng-repeat that includes checkboxes. <table> <tr ng-repeat="address in contactInfo.Addresses"> <td>{{address.DisplayType}}</td> <td>{{address.AddressLine1}}</td> <td>{ ...

Is your Scrollmagic failing to function once your website is uploaded to the server?

My website incorporates Scrollmagic to dynamically load sections (changing opacity and adding movement) as users scroll through it. Everything functions perfectly fine when I preview the HTML file on my computer, but once I uploaded it to my hosting serv ...

Utilizing NextJS to retrieve cookie data within React components

Currently, I am working with a Next.js frontend and an Express backend. For authentication, I am utilizing cookies and have set up protected routes using Next.js middleware. The next step in my project involves accessing the cookie response within React ...

How to temporarily toggle an event on and off using jQuery

Is there a way to control the activation and deactivation of a jQuery event? I currently have this functioning code that runs when the page is ready: $(".panzoom").panzoom({ $zoomIn: $(".zoom-in"), $zoomOut: $(".zoom-out"), $zoomRange: $(".zoo ...

Navigate to the date selector and select the following month

<button class="mat-calendar-next-button mat-icon-button" mat-icon-button="" type="button" ng-reflect-disabled="false" aria-label="Next month"><span class="mat-button-wrapper"></span><div class="mat-button-ripple mat-ripple mat-button-r ...

The magnifying glass icon is missing from the autocomplete search feature

After creating an autocomplete search functionality that queries my mysql database, I encountered a slight issue. Here is the code snippet showcasing my implementation: <div class="search-bar"> <div class="ui-widget"> <input id="ski ...