Leveraging regular expressions for handling apostrophes

I need help with a function

function convertToTitleCase(sentence: string) {
  return sentence.replace(/\b\w/s, word => word.toUpperCase());
}

Current output: Men's apparel

Desired output: Men's Apparel

Can anyone assist me in achieving this?

Answer №1

Utilize

function convertFirstLetterToUppercase(sentence: string) {
  return sentence.replace(/(?<![\w'])\w/g, char => char.toUpperCase());
}

CLARIFICATION

--------------------------------------------------------------------------------
  (?<!                     searching for absence of:
--------------------------------------------------------------------------------
    [\w']                    any characters from: alphanumeric characters (a-z,
                             A-Z, 0-9, _), '''
--------------------------------------------------------------------------------
  )                        end of search
--------------------------------------------------------------------------------
  \w                       alphanumeric characters (a-z, A-Z, 0-9, _)

Keep in mind the g flag is used to replace all occurrences, not s.

Answer №2

If you want to capitalize all words in a string, you can utilize the callback function of the replace method.

function capitalizeAllWords(str: string) {
    return str.replace(/'[a-z]|\b([a-z])/g, (m, g1) => g1 ? g1.toUpperCase() : m);
}

In this regex pattern, you capture the letters you want to uppercase in group 1 and match the rest to be left untouched.

'[a-z]|\b([a-z])

Here's a breakdown:

  • '[a-z] will match any occurrence of ' followed by a lowercase letter
  • | Or
  • \b([a-z]) uses word boundaries to avoid partial matches and captures a lowercase letter in group 1

To see how this works, check out the Regex demo.

const regex = /'[a-z]|\b([a-z])/g;
const str = "Men's apparel $test";
let res = str.replace(regex, (m, g1) => g1 ? g1.toUpperCase() : m);
console.log(res);

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

Instructions for importing a CSV file into PostgreSQL with Node.js

Just dipping my toes into the world of node js. I've got a csv file sitting on my local system that I'm eager to upload to my local PostgreSQL Database using node js. Here's what I've been experimenting with: var csv = require(' ...

Error: Encountered an unexpected token while trying to parse multiple form functions

I recently added the following submission function to my .js file: $( "form" ).on( "submit", function( event ) { event.preventDefault(); var data = $( this ).serialize(); $.ajax({ type: "POST", url: "content/rev/a_sub ...

What is the best way to incorporate a dropdown menu into existing code without causing any disruption?

I've come across this question multiple times before, but I still haven't found a suitable answer or solution that matches my specific situation. (If you know of one, please share the link with me!) My goal is to create a basic dropdown menu wit ...

Error in Typescript compilation in Visual Studio Team Services build

I am currently working on an angular2 web application using Typescript 2.0. I have successfully installed version 2.0 locally in my Visual Studio and updated the tag for Typescript version in my project. The local build in VS works perfectly fine, but when ...

Guide to generating a div element with its contents using JSON

On my webpage, there is a button that increases the "counter" value every time it's clicked. I am looking to achieve the following tasks: 1) How can I generate a json file for each div on my page like the example below: <div class="text1" id="1" ...

Angular (4, 5, 6, 7) - An easy guide to implementing slide in and out animations using ngIf

How can you implement a basic sliding animation in Angular4 to show and hide a container element? For example: <div *ngIf="show"> <!-- Content --> </div> Slide the content in (similar to jQuery's slideDown() method) from top t ...

Using expressJS and MongoDB to create a secure login and registration system

I am interested in adding a login/register function to my expressJS API. Currently, I am only inserting the password and email into my database. I would like this function to first check if a user with this email is already in the database - if yes, then s ...

What is the reason behind Firefox failing to display a linear gradient when the background-size values are more than 255px?

I am working on creating a grid overlay using an absolutely positioned non-interactive div. My approach involves using the repeating-linear-gradient property as suggested by others for this purpose. The functionality works smoothly in Chrome, but I seem to ...

Eliminating the spacing between elements to create a seamless design

Currently immersed in the creation of a new website, I am facing an issue with closing the margin gap on the right side of the page. The problem persists despite setting the body's margin to 0px. Any assistance in resolving this issue would be greatly ...

altering dimensions in three.js

My question may seem a bit silly, but it's about resolution in THREE.js. I have experience with OpenGL and some frameworks related to it, so naturally, I became interested in webGL and Three.js. After trying out some simple demos, I decided to create ...

Enhancing socket.io with the incorporation of a variable

I was looking for a way to connect an object named player to various sockets. My initial approach was to simply do socket.prototype.player = whatever; However, no matter what I attempt to prototype, it always returns undefined. Does anyone have a solution ...

Retrieving JSON information using Ajax to enhance Cytoscape visualization

Looking to share a network using Cytoscape web or, if possible, cytoscape.js. Due to the size of my data, I find it easier to export it from Cytoscape desktop and grab it using ajax in my HTML. Previously, before version 3.1.0 of Cytoscape, I could export ...

What methods do web browsers use to detect when a user has viewed a custom image on a webpage?

As I work on creating a website to sell handmade crafts, it is essential that high-quality images are displayed for each product. In order to address SEO issues, I am considering loading the images asynchronously only when the user reaches the thumbnail ...

Changing the color of each line within a BufferGeometry using Three.js

This example demonstrates drawing lines with the same color. I aimed to change the color of each line and here are the modifications I made: Introducing attribute const colors = new Float32Array(MAX_POINTS * 3); geometry.setAttribute('color' ...

In the matrix game, if a user chooses two balls of the same color, those two matching color patterns will be eliminated

I am currently working on a matrix game with the following condition: When a user selects two balls of the same color, they will destroy the two patterns with the same color. I have successfully implemented horizontal and vertical selection. However, I ...

Modifying an array without altering the reference

Perhaps my approach is not quite right, so please provide feedback if necessary! Imagine having an Array that represents some valuable data. var initial = ['x', 'y']; var duplicate = initial; initial.push('z'); console.log(i ...

What is the relationship between dependencies in the `useEffect` hook and state within React?

I have a good understanding of how React's "useState" hook operates. State in React is essentially a list of values associated with specific components, and each "useState" call has an index that references a specific state value. When the React rende ...

Validation of form fields appears to be disregarded

I seem to have overlooked a simple issue with this form field validation method. It has worked effectively for me in the past, but now, despite checking all file paths, every time I submit the form, it sends an email regardless of the field content. You c ...

Leveraging AJAX for sending information to an API

A script I've written utilizes AJAX to communicate with a PHP-based API. The first part of the script is responsible for loading trade history: $(document).ready(function () { var orders = $('#History ul'); ...

Utilizing the Express-busboy npm package to generate a new directory within the public folder of

While working on my controller, I encountered an issue when trying to readFile sent from the browser via AJAX. Unexpectedly, a directory was created in my public folder with a name like '3d6c3049-839b-40ce-9aa3-b76f08bf140b' -> file -> ...