Change the initial characters of a string according to specific categories

What is the best way to capitalize the first letter of a string based on specific conditions like those shown below?

  • booking_engineBooking Engine
  • booking-engineBooking Engine
  • bookingEngineBooking Engine
  • crsProviderCRS Provider
  • crs_ProviderCRS Provider
  • crs-ProviderCRS Provider

I have attempted to achieve this with the function provided below, however, it does not fully meet the requirements for the last three scenarios.

beautifyString(key: string): string {
    let separateWord: string[];

    if (key.includes('_')) {
        separateWord = key.split('_');
    } else if (key.includes('-')) {
        separateWord = key.split('-');
    } else {
        separateWord = key.split(/(?=[A-Z])/g);
    }

    for (let i = 0; i < separateWord.length; i++) {
        separateWord[i] =
            separateWord[i].charAt(0).toUpperCase() +
            separateWord[i].substring(1);
    }

    return separateWord.join(' ');
}

Answer №1

As mentioned previously, I want to clarify that I may not have the exact criteria you're looking for, but the following function enhances a string and meets all specified conditions by splitting it using any of the methods below:

  • Separating at - and converting to title case,
  • Dividing at _ and converting to title case,
  • Or breaking down camelCase notation and converting to title case.

You can perform additional string manipulations later on (e.g. capitalizing the first three letters as shown in your result samples).

const beautifyString = (word) => {
  let result = "";
  const splitters = ["-", "_"];

  if (word.includes(splitters[0])) result = word.split(splitters[0]);
  else if (word.includes(splitters[1])) result = word.split(splitters[1]);
  else result = word.replace(/([a-z])([A-Z])/g, "$1 $2").split(" ");

  return [...result.map((e, i) => e[0].toUpperCase() + e.slice(1))].join(" ");
};

console.log(beautifyString("booking_engine"));
console.log(beautifyString("booking-engine"));
console.log(beautifyString("bookingEngine"));
console.log(beautifyString("crsProvider"));
console.log(beautifyString("crs_Provider"));
console.log(beautifyString("crs-Provider"));

TypeScript Version

const beautifyString: (word: string) => string = (word: string) => {
  let result: string[] = [];
  const splitters = ["-", "_"] as const;

  if (word.includes(splitters[0])) result = word.split(splitters[0]);
  else if (word.includes(splitters[1])) result = word.split(splitters[1]);
  else result = word.replace(/([a-z])([A-Z])/g, "$1 $2").split(" ");

  return [
    ...result.map((e: string, i: number) => e[0].toUpperCase() + e.slice(1)),
  ].join(" ");
};

console.log(beautifyString("booking_engine")); // Booking Engine
console.log(beautifyString("booking-engine")); // Booking Engine
console.log(beautifyString("bookingEngine"));  // Booking Engine
console.log(beautifyString("crsProvider"));    // Crs Provider
console.log(beautifyString("crs_Provider"));   // Crs Provider
console.log(beautifyString("crs-Provider"));   // Crs Provider

Edit

If you wish to capitalize the first three letters, a good approach is to define a dynamic function specifically for this task. Then, simply nest the function calls accordingly.

const beautifyString = (word) => {
  let result = "";
  const splitters = ["-", "_"];

  if (word.includes(splitters[0])) result = word.split(splitters[0]);
  else if (word.includes(splitters[1])) result = word.split(splitters[1]);
  else result = word.replace(/([a-z])([A-Z])/g, "$1 $2").split(" ");

  return [...result.map((e, i) => e[0].toUpperCase() + e.slice(1))].join(" ");
};

const capitalizeFirstLetters = (word, amount) =>
  word.slice(0, amount).toUpperCase() + word.substr(amount, word.length);

console.log(capitalizeFirstLetters(beautifyString("crs_Provider"), 3));

TypeScript Version

const capitalizeFirstLetters: (word: string, amount: number) => string = (
  word: string,
  amount: number
) => word.slice(0, amount).toUpperCase() + word.substr(amount, word.length);

console.log(capitalizeFirstLetters(beautifyString("crs_Provider"), 3));  // CRS Provider

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

exploring alternatives to ng-container in angular-4.x for selecting elements

Currently in my Angular 4.x project, I have a component using the Selector 'abc' as shown below: @Component({ selector: "Abc", templateUrl: "Abc.html", styleUrls: [ "Abc.css" ] }) However, the "Abc" tag is also present in the DOM, b ...

Having trouble selecting a subset of data from an AJAX request using Jquery?

I have successfully implemented a modal for form submission. However, I am encountering an issue with replacing a part of the modal with a section of the data retrieved from the ajax call. $.ajax({ url: actionUrl, method: 'post', data: dataToSen ...

Exploring the topic of AngularJS unit testing and working with httpBackend timeouts

I have experience in the testing world, particularly with TDD using tools like mocha, sinon, chai, and nodejs. Recently, I've been finding AngularJS testing a bit challenging to grasp and implement. Currently, I am trying to test the simplest method ...

What is the most effective method for disregarding undefined values?

Implementing a project using Vue.js and Vuex, I am retrieving data from an API that functions as a content-management system. The product class in the CMS possesses numerous properties that can be populated by the user, such as; { "title": &quo ...

Is it feasible to bypass the dialog box on beforeunload?

Currently, I am utilizing jQuery's bind method like so: $(window).bind('beforeunload', function() { //my code return ""; } In Mozilla Firefox and IE8, everything works smoothly without including the "return "";" statement. No pesk ...

Trouble activating Bootstrap 4 checkbox through JavaScript integration

When clicking on a table row, I am able to add the class active with JavaScript. However, when trying to click on a checkbox, an error occurs. Check out the live Codepen link here Below is the custom code snippet: $('.dashboard-table-tbody tr&apo ...

How is it possible for TypeScript to permit an inaccurate comparison like boolean === undefined?

Encountering the peculiar behavior of TS. const isItLanding = false; if (isItLanding === undefined) { // valid return ...; } However, in this instance const isItLanding = 1; if (isItLanding === 'undefined') { // error return ...; } Why do ...

A solution to replace Object.entries() for Internet Explorer compatibility in ReactJS

After spending several weeks developing a web application, everything was going smoothly until I reached the testing phase in Internet Explorer. To my surprise, one issue remained unresolved - the lack of support for Object.entries(). Despite my attempts t ...

Express Producing Empty Axios Post Request Body

I am facing an issue with sending two text data pieces from my React frontend to an Express backend. Whenever I use the post command with Axios, the body appears as {} in the backend and becomes unusable. Below is the code that I am using. Client (App.js) ...

I am having trouble toggling radio buttons in React

class VoiceSelector extends Component { constructor(props){ this.handleCheck = this.handleCheck.bind(this); } state={ voices : [ {"Voice":"Indian English Female Voice 1"}, {"Voice":&qu ...

In the MUI v5 framework, when using nested modals, both the parent and child modal instances will close simultaneously

Here is the reproduction of my issue on codesandbox: https://codesandbox.io/s/trusting-babbage-ovj2we?file=/src/App.js A nested modal has been created where the parent modal opens a button leading to the child modal. The useState of the parent modal has b ...

Fixing errors with observables in an Angular 2 project using Rx

var foo = Observable.create(function(observer){ try{ console.log('hey there'); observer.next(22); throw new Error('not good at all'); setTimeout(function(){ observe ...

How can a React app be developed offline?

I am currently working offline with no access to the internet. Node.js is already installed on my system, but I encountered an error when trying to run the command npm create-react-app. Is there a way for me to execute npm commands and set up a react app ...

Using WebdriverIO with Angular to create end-to-end tests in TypeScript that involve importing classes leads to an error stating "Cannot use import statement outside a module."

I am facing an issue while trying to set up a suite of end-to-end tests using wdio. Some of the tests utilize utility classes written in TypeScript. During the compilation of the test, I encountered the following error: Spec file(s): D:\TEMP\xx& ...

Using AJAX to upload jQuery file - sharing PHP variables

After setting up the blueimp jQuery file upload, I've encountered a problem that's stumping me. My goal is to retrieve a PHP variable that's posted when the file is uploaded and execute some PHP code if it exists. I have made modifications ...

Can a for loop be implemented within a mongoose schema method?

Is there a way to modify this for loop so that it runs through the entire array instead of adding one by one? Any suggestions? EndorsedSkillSchema.methods = { async userEndorsedSkill(arr) { for (var i = 0; i < arr.length; i++) { const skil ...

implement a new directive in AngularJS that references another directive in HTML

Check out the Fiddle here Upon button click, a modal window appears. Inside this modal, there is a <template-placeholder></template-placeholder>. When the button is clicked, an if-check is performed to ensure it's the correct button. If ...

Woops! Looks like there's an issue - the property 'url' is not defined and cannot be

I am currently working on fetching data from a REST API using angular2, and everything seems to be going smoothly. However, I have encountered an error that only appears in the console when calling {{content.img.url}}. Interestingly, the code executes fine ...

Error message occurs when using Typescript with es2017 target, indicating a potential need for a loader despite successful project builds in es5

We are working on a typescript react 'main' project. In the package.json file, there is a dependency on another internal library that we utilize. The 'main' project builds successfully when both projects are set to target es5. However, ...

`Designing a UI in Ionic version 2`

Is it possible to create a layout page in an Ionic v2 application so that the navbar and sidemenu can be displayed on every page without having to add them individually to each page? For example, ASP.NET uses master pages for websites to contain component ...