Separate a string based on a capital letter or numeric characters

I'm currently working on a TypeScript pipe to split a PascalCase string, but I also want it to split on digits and consecutive capital letters. The challenge is that my current implementation only works in Chrome because Firefox doesn't support lookbehinds. How can I achieve this without using lookbehinds?

transform(value: string): string {
        let extracted = '';
        if (!value) {
            return extracted;
        }

        const regExSplit = value
            .split(new RegExp('(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|(?<=[0-9])(?=[A-Z][a-z])|(?<=[a-zA-Z])(?=[0-9])'));
        for (let i = 0; i < regExSplit.length; i++) {
            if (i !== regExSplit.length - 1) {
                extracted += `${regExSplit[i]} `;
            } else {
                extracted += regExSplit[i];
            }
        }

        return extracted;
    }

For example, the string ANet15Amount should be transformed into A Net 15 Amount. Note that the regex mentioned above can also handle camelCase strings.

Answer №1

What if we try using a simpler pattern like this for matching and then joining the results with space.

let str = `ANet15Amount`;

let camel = str.match(/[A-Z]+(?![a-z])|[A-Z]?[a-z]+|\d+/g).join(' ');

console.log(camel);

Initially, I considered using just [A-Z][a-z]*|\d+, but that would split ABCDefg123 into A B C Defg 123, which is different from what your current function does by transforming it into ABC Defg 123.

There's a slight distinction still. Your method turns A1B2 into A 1B 2, while this one changes it to A 1 B 2, which seems more accurate, don't you think?

Answer №2

To update the content, you can utilize this expression: replace any capital letter [A-Z] or series of numbers \d+ with a space plus the matched content " $1". The first character is excluded to prevent adding a space at the start of the resulting string by applying a negative lookahead at the beginning of the line (?!^):

// ...

return value.replace(/(?!^)([A-Z]|\d+)/g, " $1");

For instance:

let value = "ANet15Amount";

let result = value.replace(/(?!^)([A-Z]|\d+)/g, " $1");

console.log(result);

Answer №3

Give this regex a try: [A-Z]?[a-z]+|[A-Z]|[0-9]+

  • Find 0 or 1 uppercase letter directly followed by 1 or more lowercase letters
  • or find 1 uppercase letter
  • or find 1 or more digits

Test it out in the generator here: https://regex101.com/r/uBO0P5/1

Answer №4

Depending on the conventions of the string, the complexity may vary.

// Here 'TIMES' & 'with' are separated (example 2)
const str = 'SplittingStringsIsFunTimesA100000aaaTIMESwithFollowUp';

// Here 'TIMES' & 'With' are separated (example 3)
const str2 = 'SplittingStringsIsFunTimesA100000aaaTIMESWithCAPITAL5FollowUp';


// 1. USING REGEX - MATCH
console.log(
  '1. USING REGEX:\n',
  str
  .match(/(\d+|[a-z]+|[A-Z][a-z]*)/g)
  .join(' ')
);


// 2. USING REGEX - MATCH (KEEP ALL CAPITAL CHARS)
console.log(
  '2. USING REGEX (GROUP ALL):\n',
  str
  .match(/(\d+|[a-z]+|([A-Z]([A-Z]+|[a-z]*)))/g)
  .join(' ')
);

// 3. USING REGEX - MATCH (KEEP CAPITAL CHARS BUT LAST)
console.log(
  '3. USING REGEX (GROUP BUT LAST):\n',
  str2
  .match(/(\d+|[a-z]+|([A-Z]([a-z]+|([A-Z]+(?![a-z]))?)))/g)
  .join(' ')
);


// 4. USING SPLIT - FILTER
console.log(
  '4. USING SPLIT:\n',
  str2
  .split(/(\d+|[A-Z][a-z]*)/)
  .filter(v => v !== '')
  .join(' ')
);

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

Sending data from a Node.js backend to a React.js frontend using res.send

How can I pass a string from my nodejs backend using res.send? app.post("/user", (req,res) => { console.log(req.body.email); res.send('haha'); }); I need to perform certain operations on the front end based on the value of the string retriev ...

When the previous textbox is filled, the cursor will automatically move to the button

Utilizing an RFID reader where students tap their ID to display basic info, a hidden button on the form opens a modal with various purposes for selection. The challenge is shifting focus of cursor to the button and automatically clicking it when the last ...

Tips for interacting with a custom web component using Selenium WebDriver

As a newcomer to writing selenium tests, I am attempting to create an automated test for a carousel feature on our homepage. The objective is to click on one of the carousel navigation buttons and then confirm that a specific inline style has been applied ...

Retrieve both the keys and values from a deeply nested JSON object

My goal is to retrieve JSON data with a specific structure as shown below: {"Points": {"90": {"0": {"name": "John Phillip", "slug": "john"}, {"1&q ...

Bootstrap: The search icon button within the input box breaks away from the input box on resolutions other than desktop

I am attempting to place a Search Icon Button inside the Search Input Box while using Bootstrap. Although everything appears correctly at Desktop resolution, at non-desktop resolutions when the menu items collapse into a dropdown, the button and input box ...

Connecting AngularJS with select options

I am currently developing a checkout feature that calculates shipping prices based on the selected country. If the user picks United States, it should display US. For any other country selection, it should show Not US While the shipping function correctly ...

Calculate the duration in seconds using the console

Is it possible to display the time of an action in seconds instead of milliseconds using console.time? Below is my code: console.log('start load cache'); console.time('cache load ok executed in') // loading from mongo console.timeEnd( ...

Unable to utilize Socket.io version 2.0.3

When it comes to developing a video chat app, I decided to utilize socket.io. In order to familiarize myself with this library, I followed various tutorials, but unfortunately, I always encountered the same issue. Every time I attempted to invoke the libr ...

The try and catch block in JavaScript is failing to correctly capture the HTTP status

I have a function that successfully posts JSON to an API endpoint. Here is the code I am using: function sendValuesPageLoad(){ var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function () { try { if (xhr.readyState === ...

Webpage featuring tabs aligned horizontally

Can anyone guide me on setting up horizontal tabs similar to the design in this image: https://i.sstatic.net/ewXO4.png? Below is the code snippet: <label class="formlabel">Title 1:</label> <div id="radio_form"> <label><inpu ...

"Encountering a problem with installing packages on Node.js through npm

After spending the last 2 hours scouring StackOverflow and Google, I've come to the decision to seek help here. The issue I'm facing is that I'm unable to install any packages using npm. Specifically, when trying to install jQuery (as well ...

What could be causing the failure of my yup validation schema for a string array?

Can anyone provide insight into why this validation issue is occurring? I am implementing a schema using yup to ensure that the data within an array are strings. Below is the yup schema I am working with: signUpSchema: async (req, res, next) => { ...

Angular seems to be disobeying the CSS rules

Exploring the world of Angular and delving into its usage of CSS has raised a question in my mind. As far as I understand, a component in Angular strictly adheres to the CSS styles declared within it and remains unaffected by any external CSS rules. The s ...

When combining Puppeteer with Electron, an error stating "Browser revision not found" may occur. However, this issue does not arise when running with Node

My attempts to make Puppeteer work in Electron have been with various versions of Puppeteer (v5.4.0, v5.4.1, and v5.5.0), on Windows 10/MacOS, and with different Node versions (v12, v14.0.1, v15.0.3). Trying a simple puppeteer.launch() in the main process ...

Retrieve the JSON data by passing the variable name as a string

There are JSON files embedded in the page, like so: <script type="text/javascript" language="javascript" src="json/divaniModerni.json"></script> <script type="text/javascript" language="javascript" src="json/divaniClassici.json"></scr ...

Tips for retrieving corresponding values from a TypeScript dictionary object?

I am currently working with a dictionary object that is filled in the following manner: const myDictionaryElement = this.myDictionary["abc"]; In this case, myDictionaryElement contains the values: ACheckStatus: "PASS" QVVStatus: "READY" VVQStatus: "READ ...

Concealing a div element within HTML using JavaScript Document Object

Can anyone assist me with hiding a div element using JavaScript in my game development project? I must be making an error somewhere, but I'm not sure what it is. Here is the code that I have: HTML: <div id="stats"> <table border="1"> ...

Variable not defined, scope problem

Currently, I am attempting to modify the state of an object within an array in React by utilizing Immutability Helpers. handleChange = (itemInput, itemNum = null) => event => { this.setState({ rows: update(this.state.rows, { itemNu ...

Struggling with Responsiveness: Challenges with Detailed Information and Image Grid Design

Encountering challenges in achieving the desired responsiveness for a grid layout consisting of details and an image. The layout displays correctly on desktop screens, with details on the left and the image on the right. However, on mobile screens, the ima ...

Time for the browser to evaluate javascript code has arrived

We are looking to enhance the speed at which our Javascript files load in the browser. Although our own Javascript files are simple and small, larger libraries like jQuery and KendoUI take a considerable amount of time to evaluate. We are interested in fin ...