Mastering intricate string manipulation using JavaScript regular expressions

I have a JavaScript/Node JS program that generates meaningful names according to the following rule:

Input: "tenancy_account__accountPublicId__workspace__workspacePublicId__remove-user__userPublicId"

Expected output: "TenancyAccountAccountPublicIdWorkspaceWorkspacePublicIdRemove-userUserPublicId"

Rules:

  1. Replace any character with zero or more underscores with the non-underscored uppercase equivalent. Example: x | __*x => X
  2. If there is an extra underscore at the end, remove it.

This function has been implemented so far, but I am open to better alternatives:

const convertBetterString = (input) => {
    const finalString = [];
    if (input && input.includes('_')) {
        const inputStringSeparation = input.split('_');
        if (inputStringSeparation.length > 1) {
            if (inputStringSeparation[inputStringSeparation.length - 1] === '') {
                inputStringSeparation.splice(inputStringSeparation.length - 1, 1);
            }
            inputStringSeparation.forEach((val, index) => {
                if (val === '' && inputStringSeparation[index + 1]) {
                    const actualString = inputStringSeparation[index + 1];
                    const formattedString = actualString.charAt(0).toUpperCase() + actualString.slice(1);
                    finalString.push(formattedString);
                }
            });
            return finalString.length > 0 ? finalString.join('') : inputStringSeparation.join('');
        } else {
            return input.charAt(0).toUpperCase() + input.slice(1);
        }
    } else {
        return input;
    }
}

Answer №1

Techniques for manipulating strings

const capitalizeFirstLetter = str => str.slice(0,1).toUpperCase() + str.slice(1); // more tests can be added

const inputString = "tenancy_account__accountPublicId__workspace__workspacePublicId__remove-user__userPublicId"
const newString = inputString.split(/_+/)
  .map(word => capitalizeFirstLetter(word))
  .join("")
console.log(newString)

Using regex with optional chaining

const stringInput = "tenancy_account__accountPublicId__workspace__workspacePublicId__remove-user__userPublicId_"

const modifiedString = stringInput.replace(/(?:_+|^)(\w)?/g, (_,letter) => letter?.toUpperCase() ?? "")

console.log(modifiedString)

Detailed explanation

(?:_+|^) looks for one or more underscores OR the start of a string
(\w)? captures 0 or 1 alphanumeric character

(_,letter) => letter?.toUpperCase() ?? "")
ignores matches and capitalizes any letters found, including those after trailing underscores

Answer №2

If you need to manipulate a string in JavaScript, you can try this code snippet:

const text = "customer_order__orderId__product__productId__add-user__userId__";
const updatedText = text
    .replace(/(?:^|_)_*([^\s_])|_+$/g, (_, character) => character ? character.toUpperCase() : '')
console.log(updatedText);

The regular expression /(?:^|_)_*([^\s_])|_+$/g is used to match specific patterns within the string:

  • (?:^|_) - represents the beginning of the string or an underscore
  • _* - signifies zero or more underscores
  • ([^\s_]) - Group 1: any character that is not a space or an underscore
  • | - or
  • _+$ - one or more underscores at the end of the string

In the replacement function

(character) => character ? character.toUpperCase() : ''
, all underscores are removed and any matched character is converted to uppercase.

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

Encountering repeated requests (duplicating calls) for each API request while using AngularJS with a JWT authentication token

I'm experiencing a problem with AngularJS(2/4) while attempting to make API calls. The issue arises when each API request contains a JWT Auth Token header, resulting in duplicate API calls. The first request returns no response (despite receiving a 20 ...

Testing API route handlers function in Next.js with Jest

Here is a health check function that I am working with: export default function handler(req, res) { res.status(200).json({ message: "Hello from Next.js!" }); } Alongside this function, there is a test in place: import handler from "./heal ...

Guide on generating a route using coordinates in a threejs environment

Currently, I am working with an array of coordinates obtained from the Google Maps Navigation API. I have successfully plotted these coordinates on a sphere, however, my objective is to extract the shape of the path by combining all the coordinate points ...

Guide to setting up an automated process in PHP

When setting up a tournament interface on my page: Users utilize functions like fopen() and fwrite() to create tournaments. The created tournaments must only start after a specific time, for example, 1 hour. This delay allows other users to join the tour ...

Encountering an issue with Vue JS axios request and filter: the function this.XX.filter is not operational

I am encountering challenges while trying to implement a basic search feature on a JSON file obtained through an API. Each component works independently: I can successfully retrieve data from the API, perform searches on non-API data, and even search cert ...

Is it possible to replace a server-side templating engine with Angular 2's server-side pre-rendering?

As a novice in web development, I have recently been exploring angular 1.x, react.js, and angular 2 (eventually deciding on angular 2). Lately, I've been intrigued by the concept of server-side pre-rendering. In my understanding, this process is ...

Utilizing the JQuery .not() method to fade out all div elements except for the one that is selected and its corresponding children

I have a grid consisting of images, each with a hover function that changes the opacity of a div. The image is set as a background image, while the information is placed within a div in each grid-item. <div class="grid"> <div class="grid-it ...

Retrieve the output from PHP in JSON format and then utilize jQuery to parse it

I am currently working on a jQuery function $.post(file.php), where the data is being sent to "file.php" and returned in JSON format using json_encode(). Although I am able to successfully retrieve the result, I am unsure how to separate the individual i ...

Tips for improving the performance of MongoDB queries in a Node.js environment

I am currently facing an issue with my code running in nodejs where I need to call a MongoDB query with aggregation properties using callbacks. However, the code is not functioning as expected. I want the code to run asynchronously so that once the MongoDB ...

The error message reads: `'Icon' is not included in the export list of 'antd'`

I have recently developed a React application and I'm incorporating Ant Design (antd) into it. However, I encountered an issue in one of my project files where I am unable to use the Icon tag. It seems like this is a known problem in ANT V4. The impo ...

How to replace all square brackets in a Java string

I am trying to figure out how to remove square brackets from a string, but I can't seem to get it right. String str = "[Chrissman-@1]"; str = replaceAll("\\[\\]", ""); String[] temp = str.split("-@"); System.out.println("Nickname ...

Executing jQuery on page update can be achieved by utilizing event handlers to trigger

I have implemented jQuery multi-select to enhance the user experience of my Django app's multiselect feature. Upon initially rendering my page, I included the following script to bind any elements with the class 'multiselect' to the jQuery m ...

Guide to creating a rising or waving effect for text using CSS or JavaScript without the need for animation

Is there a way to style dynamic text like this using HTML? https://i.sstatic.net/NQ9Cs.jpg I'm open to using CSS or Javascript, as long as it does not involve animation. ...

Tips on incorporating a changing variable into a JavaScript Shader

I have successfully created a primitive sphere using THREE.SphereGeometry and applied a displacement shader to give it a bumpy effect. My goal now is to animate the scale of the bumps based on input volume from the microphone. Despite my efforts, I am stru ...

Using Vue3 to set attributes on web components

I recently developed a self-contained web component using Vite and Vue3 to replace outdated jQuery libraries. When this component is rendered in HTML, it appears like this: <custom-datepicker id="deliveryTime"> #shadow-root <div> ...

Alter the Color of the 'div' According to the Background

At the bottom right of my website, there is a black chatbot icon. The web footer also has a black background. To create a clear contrast, I have decided to change the color of the chatbot to white as users scroll to the bottom of the page. I implemented t ...

Validating multiple fields that are added dynamically using jQuery

I am facing an issue with form validation using jQuery. The problem is that when one field is valid, the form gets submitted automatically. Here is a link to my code: http://jsfiddle.net/cvL0ymu7/. How can I ensure that all fields are validated before subm ...

An issue has occurred: The necessary parameter (Slug) was not included as a string in the getStaticPaths function for the /post/[Slug] route

Hello, I've recently embarked on a tutorial journey to create the ultimate Modern Blog App using React, GraphQL, NextJS, and Tailwind CSS. However, I encountered an error that's giving me some trouble specifically when trying to access a post. He ...

React drag and drop feature now comes with autoscroll functionality, making

I am encountering an issue with my nested list Items that are draggable and droppable. When I reach the bottom of the page, I want it to automatically scroll down. Take a look at the screenshot below: https://i.sstatic.net/ADI2f.png As shown in the image ...

Tips on avoiding page refresh when hitting the submit button:

I am working on a form that consists of one input field and one submit button. <form method='POST' action='' enctype='multipart/form-data' id="form_search"> <input type='hidden' name="action" id="form_1" va ...