Regular expression pattern for consistently capitalizing the phrases "CA" and "USA" in an address string

end_address = 'joe's home, 123 test avenue, los angeles, ca, usa 90210';

end_address = end_address.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});

The outcome of this code will be:

Joe's Home, 123 Test Avenue, Los Angeles, Ca, Usa 90210

However, the preferred result is:

Joe's Home, 123 Test Avenue, Los Angeles, CA, USA 90210

Is there a way to modify the code so that "CA" and "USA" are always in uppercase like the desired outcome?

Answer №1

Here is a solution that will do the trick:

address = 'jOe place, 555 test street, sacramento, ca, usa 95814'.capitalize();

address = address.replace(/\b(usa\b|ca\b|\w)/g, function(txt) { return txt.toUpperCase(); });

alert(address);

To start off, all letters are made lowercase. Then, the regex pattern /\b(usa\b|ca\b|\w)/g is used to capitalize the first letter of specific words like "usa" and "ca".

Answer №2

To ensure consistency in the pattern, it is necessary to perform a second iteration through the string.

let result = address_end
  .replace(/\w\S*/g, function(word){
    return word.charAt(0).toUpperCase() + word.substr(1).toLowerCase();
  }).replace(/(\w{2}), (\w+) (\d{5}(-\d{4})?)$/, function(match, state, country, zipCode) {
    return state.toUpperCase() + ", " + country.toUpperCase() + ", " + zipCode;
  });

Answer №3

Here's a simple method to achieve the desired outcome:

let address = address.replace(
    /([a-z]{2}),\s*([a-z]{3})\s*(\d{5})$/i,
    function(match, state, country, zip) {
        return state.toUpperCase() + ", " + country.toUpperCase() + " " + zip;
    })

This code snippet will perform the replacement in one go, specifically targeting the state and country (assuming they are located at the end of the string).

Check out the regex in action on Regex101

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

Applying style changes to the height on scroll event in Javascript for Chrome, Firefox, and Internet Explorer

I am working on triggering an event when scrolling to a specific height. I have code that successfully adds a style in Chrome, but it is not functioning properly in IE. Can anyone provide assistance? myID = document.getElementById("subnav"); var mySc ...

Steps to launching a URL in a new window on Internet Explorer

I want it so that when button1 is clicked, the URL opens in a new window using Internet Explorer. ...

"I'm trying to incorporate react-datepicker into my ReScript application, but I'm struggling to

I am attempting to incorporate an external library like react-datepicker into my project. Below is the code snippet and how I am using it: module DatePicker = { @react.component @module("react-datepicker") external make: () => React.eleme ...

What are some ways to condense this Angular/TS code for improved performance and readability?

I am in need of assistance with refactoring a method called getBaseUrl(). This method assigns a specified string value to this.baseURL based on the input serviceType. getBaseUrl(serviceType: string, network?: string) { // Method logic to determine base ...

Insert a THREE.Points element into the scene: Error in THREE.Object3D.add: The object being added is not a valid instance of THREE.Object3D (

Trying to incorporate a system of particles, a THREE.Points element into the scene has resulted in the following error: "THREE.Object3D.add: object not an instance of THREE.Object3D. undefined" The code used for this is as follows: var backCount = 1800; ...

Create a duplicate of the table and remove specific rows

Hi there, I have a query about duplicating a table. I am looking to extract specific results and display only those results. To illustrate, here is an example in HTML code: <table class="table table-striped" id="ProfileList2"> <tbody> ...

The $timeout function in AngularJS seems to be malfunctioning

I'm attempting to add a delayed effect to my view. After a button is clicked, a message is displayed, but I want it to disappear after 2000ms. I have tried implementing a $timeout function based on recommendations I found, but it doesn't seem to ...

A guide on implementing the MVC architecture in a web application with Node.js, Express, and PostgreSQL

I'm struggling with implementing the MVC architecture in my node web app, specifically when it comes to separating the model from the controller. Currently, I have the views properly organized (all my .ejs files) and I consider my app.js as the contr ...

Decomposing a Vuex module into distinct files with Nuxt: A step-by-step guide

In the official Nuxt documentation (here), it is mentioned that 'You can choose to divide a module file into separate files: state.js, actions.js, mutations.js, and getters.js'. While there are examples of breaking down the Vuex store at the roo ...

Determining whether a string includes any elements from an array

Recently, I've embarked on a journey to learn javascript and ventured into developing a small chrome extension. This extension aims to scan item listings on a specific website for products that match keywords provided by users. I am seeking guidance o ...

Error handling in AngularJS and Firebase Promises

I am currently following a tutorial on thinkster.io and encountering some issues. The tutorial uses a deprecated SimpleLogin, so I have made the necessary code changes. However, I keep running into an error that says: TypeError: Cannot read property &apo ...

Arrange Raphael Objects in Their Relative Positions

I've been experimenting with Raphael.js recently and I've encountered an issue related to the positioning of each Raphael object. My goal is to create multiple 'canvases' without having them overlap within a predefined div on the page. ...

JavaScript code that involves manipulating dates within a nested loop

I'm currently developing a booking system where the pricing varies based on seasons that recur annually. The overall functionality is working smoothly, however, I am encountering difficulties with handling the recurring seasons. I have implemented mom ...

The functionality to disable and reenable a button after performing a calculation is not functioning properly in the code

Here's the issue I'm facing with my code: When I click the search button, a for loop prints "hi" 5000 times. Before this loop starts, I want to disable the button. However, after the console.log is done, the button should be enabled again. But fo ...

Emphasizing sections using a specific class for paragraph highlighting

Is it possible to dynamically change the style of paragraphs based on certain classes? Let's say we have a text with a list of p elements and we want to modify the styles of paragraphs that come after specific classes, such as 'alert' or &ap ...

Ways to retrieve all elements, including those that are hidden, within a CSS grid

My goal is to retrieve all the "Available Items" using Javascript in one go. However, I am facing an issue where not all of them are visible at once due to the need to manually scroll through a CSS grid. <div class="gridWrapper" data-dojo-attach-point= ...

Unable to retrieve Angular Service variable from Controller

I am facing an issue with my Angular Service. I have set up two controllers and one service. The first controller fetches data through an AJAX call and stores it in the service. Then, the second controller tries to access this data from the service. While ...

Toggle the row to expand or collapse upon clicking it

After extensive research, I have been unable to get the row expansion and collapse feature to work in my script. Here is my current script: <thead> <tr> <th width="5" class="cb"><input type="checkbox" id="cbcall" /& ...

Downloading PDF files on IOS while using Angular often results in the PDF opening in the same

I'm currently utilizing file-saver within my Angular application to retrieve a PDF generated from the backend. The library functions smoothly on desktop and Android devices, but I'm encountering issues with downloading files on iOS. Contrary to w ...

Utilizing a variable name as an object key in TypeScript

Can this be achieved? static readonly statusMapping: { [key in UploadStatus]: PopupMessageStatus } = { UploadStatus.COMPLETED : PopupMessageStatus.COMPLETED } UploadStatus is an enum with numeric values, where UploadStatus.COMPLETED = 0 p ...