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

Identifying Internet Explorer's tracking protection through feature detection in JavaScript

It seems that Soundcloud does not offer support for browsers older than IE11, possibly due to tracking protection in IE9 and IE10. Is there a simple method using javascript to detect if tracking protection is enabled? I want to filter out all users with ...

Can you confirm if the user originated from JavaScript when Ajax is sent?

Illustration: Upon using "ajax.send", the file is displayed (for example, "post.php?q=...".) However, by copying the specific "url" and pasting it into the browser with the same parameters, access can also be gained. Hence, is there a way to prevent this ...

Where is the session management functionality situated within an OAuth-enabled web application?

When creating an oauth service (such as for Facebook or Gmail) enabled web application using Angular or React, where should session management be located? Should user sessions be maintained on the hosted server or within the oauth service itself? This is ...

Having trouble with images not showing up on React applications built with webpack?

Hey there! I decided not to use the create react app command and instead built everything from scratch. Below is my webpack configuration: const path = require("path"); module.exports = { mode: "development", entry: "./index.js", output: { pa ...

How can I make a div element match the height of an image and overflow without relying on

Here is the code that I am currently working with: https://codepen.io/allen-houng/pen/ExYKYdq Additionally, you can find a gist of the code snippet below: <div class="parent"> <div class="imageWrapper"> <img class="image" src="imageurl" ...

Is it possible to create a single directive that can handle both Structural and Attribute behaviors?

Trying to develop an Angular Directive that will handle various functionalities based on config input values Dynamically add elements to the DOM based on input values (similar to ngIf) Apply styling to rendered elements Add attribute properties such as d ...

Determine the number of input tags within a div element by utilizing the closest property in jQuery

Sorry for the silly question, but I've been struggling to find a solution. Spent hours scratching my head. Here is my HTML structure: <div class= 'container'> <div class="someclass"> <input>some content</in ...

Creating a new image by converting canvas to an image and displaying it in a separate window with Ruby on Rails and

I'm having some trouble with this issue and would really appreciate your help. My goal is to convert a canvas into an image using toDataURL when a link, button, or image is clicked. Once the image is generated, I want it to open in a new window. Can ...

Guide to Binding a JSON Property (Set or Array) to an Interactive Input Form in AngularJS

My input form is structured like this: <div> <div class="form-group"> <label for="inputQuestion" class="col-sm-2 control-label">Question</label> <div class="col-sm-10"> <input data-ng-model="publication.qu ...

Is it possible to assign binary content to the src attribute of an img, audio, or video tag?

Picture this scenario: I send an ajax request to my PHP server with the name of an image file, and the server is restricted from sending a direct link to the file. Instead, it must send the file contents using PHP's readfile(); function. Now, when thi ...

Update the color of the div when all checkboxes in the hidden form are selected

Seeking help for multiple issues I'm facing with my code. Here is the link to the code. HTML for Upper Table: <div class="block"> <table> <tr> <th>Nr.</th> <th style="width: 200px">Task</th& ...

The functionality to subscribe in ts(6385) has been marked as

I am encountering an error message regarding the deprecation of the subscribe function in my code. The issue seems to be with the second part of the code for the getStarwarsHeroes function, where the .subscribe method is being deprecated. import { Injectab ...

The spreading of personalized events

I am expecting my CustomEvent to be propagated from the document to all the DOM elements. However, for some unknown reason, it is not happening. Can you point out what mistake I might be making? <html> <script> function onLoad() { var myDi ...

Manipulating Strings in JavaScript

Hi there, I'm a beginner in JavaScript and I could really use some help with the following question. So, let's say I have this string: "AB_CD.1.23.3-609.7.8.EF_HI.XBXB" The numbers 1.23.3 and 609.7.8 are completely random with two dots separat ...

Switch the ng-bind-html option

Dealing with a string in my scope, I must determine whether I want the HTML escaped or not. A boolean value helps to decide if the HTML should be escaped or left as is. Snippet Check out some of my code examples below: $scope.result = "<b>foo</ ...

How to Use Javascript to Listen for Events on a Different Web Page

Is it possible to open a popup using window.open and then subscribe to page events (such as onload) of the popup from the opener? I am looking for a method in my parent page (opener) that will execute when the popup's onload or ready event fires. Can ...

How can we wrap the Vuex store within a Vue plugin's install function?

I developed a plugin that utilizes Vuex for state management. // plugin.js import Vuex from "vuex"; import store from "./store.js"; export default { install(Vue, options) { const storeInstance = new Vuex.Store(store); Vue.pr ...

Issue with Typescript npm script including compilation and nodemon issue

After exploring various SO links, I tried to find a way to simultaneously run both tsc -w and nodemon app.js using a single command. The link I referred to is: How do I execute typescript watch and running server at the same time? Working on a node.js pr ...

Form a hierarchical data structure using a combination of three arrays

Here are three sets of data: let firstData = [ {key: value1}, {key: value2}, {key:value3} ] let secondData = [ {key: value1}, {key: value2}, {key:value3}, {key: value4} ] //same structure, different values let thirdData = [ [1,1,1,1], [1,1,1,1], [1,1,1,1] ...

Utilizing a single code base for both Web development with Angular 4 and Mobile app development with Ionic 3

I'm interested in finding out if I can utilize the same code base for both my Angular 4 web application and an Ionic 3 mobile application that I need to develop. As someone who is new to Ionic 3, I've been exploring the documentation and discove ...