Regular expressions for intricate uppercase-lowercase situations

Looking for assistance with an app that converts text to braille formatting, specifically in handling uppercase letters. The rules are as follows:

  1. Add a ":" before a single uppercase letter.

:This is an :Example

  1. Add another ":" before multiple uppercase letters and all caps words.

:This is ::ANOTHER ex::AMple, ::ALRIGHT

  1. If there are more than three consecutive uppercase words, add "-" at the beginning of the sequence and remove extra "::" within that sequence (except for the last one).

:This is -::A VERY LONG SENTENCE WITH A SEQUENCE OF ALL ::CAPS to serve ::AS ::AN :Example

  1. When transitioning from uppercase to lowercase within a word (excluding initial capitalization), add ";".

:This is my fin:A;l ::EXAM;ple

I've managed to address some of these rules using regex but struggle with others. Any insights or solutions would be greatly appreciated. Thank you!

// Adds ":" before any uppercase letter
   var firstChange = text.replace(/[A-Z]+/g,':$&'); 

// Adds ":" to double+ uppercase    
   var secondChange = firstChange.replace(/[([A-Z]{2,}/g,':$&'); 

// Adds ";" between upper and lower case
   var thirdChange = secondChange.replace(/\B[A-Z]+(?=[a-z]/g,'$&;')   

Experimented with different approaches while working with regex without much success. Open to suggestions on how to tackle this challenge effectively. Feel free to provide feedback or solutions. Thanks!

Edit: To illustrate all rules combined, here's a final example:

This is an Example. This is ANOTHER exAmple, ALRIGHT? This is A VERY LONG SENTENCE WITH A SEQUENCE OF ALL CAPS to serve AS AN Example. This is my finAl EXAMple.

The transformed version should look like this:

:This is an :Example. :This is ::ANOTHER ex::AM;ple, ::ALRIGHT? :This is -::A VERY LONG SENTENCE WITH A SEQUENCE OF ALL ::CAPS to serve ::AS ::AN :Example. :This is my fin:A;l ::EXAM;ple


SOLVED: Collaborated with @ChrisMaurer and @SaSkY to craft a code solution for the specified problem:

(Edit: Edited fourth change based on input from @Sasky)

var original = document.getElementById("area1");
var another = document.getElementById("area2");

function MyFunction(area1) {

  // Include ":" before every uppercase letter
  var firstChange = original.value.replace(/[A-Z]+/g, ':$&');

  // Add another ":" before multiple uppercase letters
  var secondChange = firstChange.replace(/([([A-Z]{2,}|\b[|A-Z]+\b)/g, ':$&');

  // Add "-" at the beginning of long uppercase sequences
  var thirdChange = secondChange.replace(/\B(::[A-Z]+(\s+::[A-Z]+){3,})/g, '-$&');

  // Remove extra "::" within long uppercase sequences
  var fourthChange = thirdChange.replace(/(?<=-::[A-Z]+\s(?:::[A-Z]+\s)*)::(?=[A-Z]+\s)(?![A-Z]+\s(?!::[A-Z]+\b))/g, '');

  // Add ";" when transitioning from uppercase to lowercase within a word
  var fifthChange = fourthChange.replace(/\B[A-Z](?=[a-z])/g, '$&;');

  // Update
  area2.value = fifthChange;
}
<html>
<body>
<textarea id="area1"  rows="4" cols="40" onkeyup="MyFunction()">
</textarea>
<textarea id="area2" rows="4" cols="40"></textarea>
</body>
</html>

Answer №1

It appears that your initial method is effective in placing single colons correctly. However, the second replacement encounters issues with single letter words like A and I. To address this, consider incorporating an additional alternation:

/([([A-Z]{2,}|\b[A-Z]+\b)/g

In order to further refine the formatting, two more replacements are needed; one to include hyphens and another to eliminate double colons.

To insert a hyphen, target sequences of three or more ::ALLCAPS combinations followed by whitespace:

/\B(::[A-Z]+(\s+::[A-Z]+){2,})/g

The \B specifier ensures caps at the start of the string are accounted for. Subsequently, replace matching instances with a hyphen and $1.

To delete double colons, utilize a more intricate approach involving lookbehind and lookahead expressions:

/(?<=::[A-Z]+\s*)::([A-Z]+)(?=\s*::[A-Z]+)/g

In this scenario, simply substitute with $1. Fortunately, Javascript facilitates variable length lookbehinds.

You can test this functionality on Regex101: https://i.sstatic.net/yyUTF.jpg

I did not review your final replacement; it seemed sound at first glance.

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

Deviations in Scriptaculous Callbacks during Movement Effects

I am looking to create a dynamic menu item that moves out 5px on mouseover and returns to its original position using Scriptaculous. I have implemented the afterFinish callback to ensure that the bump-out effect is completed before the item moves back in. ...

Maya model being loaded using Three.js

I've been following a tutorial on how to load Maya models using Three.js, which you can find here. Everything is going smoothly, but the tutorial only covers loading models with a single texture. Below is the source code snippet from the tutorial: ...

Is it important to minify JavaScript npm packages?

In my journey of creating numerous npm packages, I find myself pondering over the question: "Should JavaScript npm packages be minified?" I have always held the belief that minifying already minified code is not a good practice, which is why I have refrai ...

Duplicate the identical data retrieval query, this time utilizing a JavaScript Ajax post method

To enhance the data request query, implement a JavaScript Ajax post method to avoid page refresh when the button is pressed. This will allow for requesting another page and displaying it in a designated section on the webpage. Here's the code snippet ...

Tips for setting up electron.js on a linux operating system

Seeking guidance to successfully install electron.js on a Linux operating system. Here are the issues I'm encountering: Installation Command sudo npm i electron Terminal Output /usr/bin/electron -> /usr/lib/node_modules/electron/cli.js <a ...

Tips for maintaining the particles.js interaction while ensuring it stays under other elements

I have incorporated particle.js as a background element. By adjusting the z-index, I successfully positioned it in the background. While exploring solutions on the Github issues page, I came across a suggestion involving the z-index and this code snippet: ...

Adjust the CSS of a dynamically generated jQuery checkbox button in real-time

I am working on a project where I am creating a series of jQuery checkboxes dynamically within a loop. Here is how I am doing it: var checkbox = $('<input>').attr({type: 'checkbox', id: checkbox_id); panel.append(checkbox); panel ...

Enhance the functionality of the kendo grid by incorporating additional buttons or links that appear when the

Is there a method to incorporate links or buttons when hovering over a row in a kendo grid? I've searched through the documentation and looked online, but haven't found a solution. I'm considering if I should modify my row template to displa ...

retrieve data from an asynchronous request

Utilizing the AWS Service IotData within an AWS Lambda function requires the use of the AWS SDK. When constructing the IotData service, it is necessary to provide an IoT endpoint configuration parameter. To achieve this, another service is utilized to obta ...

Learn the process of updating a nested document within an array in MongoDB

I have a data structure as shown below: { "name":"xxxxxx", "list":[ { "listname":"XXXXX1", "card":[ { "title":"xxxxxx", "descip":"xxxxxxx ...

Unveiling the hidden: Leveraging Python to extract elements not visible in HTML, yet present in Chrome's "Inspect Element" tool

Hello Python Experts! I'm diving into the world of Python and working on a program to retrieve data from a webpage. If the page returned all the information in its HTML source, there wouldn't be an issue as it's easily viewed in Chrome. Howe ...

I am having trouble getting the color, metalness, lights, and shaders to work properly in Three JS on my

I attempted to create a simple code using Three.js for a red colored torus with a point light and a textured surface, but unfortunately, all I achieved was a black torus that rotates. It seems like the elements in this code are not functioning as expecte ...

Utilizing jQuery ajax to dynamically update map markers on Google Maps at intervals

I am currently working on a project that involves updating a Google map with a marker at regular intervals. I have an Ajax request that retrieves a single latitude and longitude coordinate, but I'm struggling to display it on the map. One option coul ...

Angular 6: Endlessly Scroll in Both Directions with Containers

Does anyone know of a library for angular 6 that allows for the creation of a scrollable container that can be scrolled indefinitely in both directions? The content within this container would need to be generated dynamically through code. For example, ...

Tips for automatically loading a new page or URL when a user scrolls to the bottom

I am working on implementing infinite scroll functionality, where a new page loads automatically when the user reaches the bottom of the page or a particular div. Currently, I have this code that loads a new page onclick. $("#about").click(function(){ ...

Positioning an element in the center of another using JQuery

Greetings! I am currently working with some elements that look like this: <div id="one">content</div> <div id="two">content</div> These elements are followed by another set of elements (without any parent, placed directly after th ...

Learn the process of adding a tag to specific text with the help of JavaScript

I am attempting to implement a feature where the selected text will have a tag added to it. Within a textarea, I have some text entered. The goal is that when I select specific text from the textarea and click a code button, it should insert the tags aro ...

Verify Radio Buttons in AngularJS

I thought validating a selection from a radio group would be simple, but I'm struggling to find the right solution. In my form, I need to ensure that at least one option is selected from the radio buttons. Using the 'required' attribute on e ...

What is the best way to display a notification on the screen when a user fails to select an option from a checkbox in PHP?

I'm currently tackling a form project where I need to trigger an alert if the user hasn't selected any options from a checklist. Despite scouring various resources for solutions, my lack of JavaScript coding skills has left me at a standstill. He ...

Is it possible to detect inline elements that have been wrapped?

I am facing a challenge with displaying an indefinite amount of in-line elements. Depending on the width of the browser, some elements may shift to a new line. I am curious to know if it is possible to identify and isolate these rows of elements, or if the ...