Using regular expressions, replace all instances of " " with ' ' based on certain conditions

I am looking to replace quotes "" with single quotes '' within a string.

string = `bike "car" bus "'airplane'" "bike" "'train'"`
  1. If a word is inside double quotes, it should be replaced with single quotes ('car' -> 'car')

  2. If there are brackets inside single and double quotes -> the outer brackets should be removed (' 'airplane' ' -> 'airplane')

Therefore, the final result should be

 `bike 'car' bus 'airplane' 'bike' 'train'`

I came across a similar regex

/(?=(?:"[^"]*?"[^"]*)+$)"([^"']*?)"/gm
but it does not meet my requirements completely, especially for the second condition

const regex = /(?=(?:"[^"]*?"[^"]*)+$)"([^"']*?)"/gm;
const str =  `bike "car" bus "'airplane'" "bike" "'train'"`;
const subst = `'$1'`;

const result = str.replace(regex, subst);

console.log('Substitution result: ', result);
// bike 'car' bus "'airplane'" 'bike' "'train'"

I could achieve this by adding two more replacements, but I believe it can be done in a better way. Here is my solution

const result = str.replace(regex, subst).replace(/"'/g, "'").replace(/'"/g, "'"); //identify if the string contains " ' and replace it with ', and vice versa for ' " -> '

Answer №1

When dealing with the sample data, it is advisable to utilize 2 capture groups and implement replace function with a callback that examines the value of one of the groups.

The task involves extracting the matched value enclosed in single quotes.

"'(.*?)'"|"([^"\s]*)"

The defined pattern identifies:

  • "'(.*?)'" It captures any character in group 1 occurring between "' and '"
  • | Alternatively,
  • "([^"'\s]+)" It captures any character other than " or a whitespace character in group 2

Feel free to test the regex here!

const regex = /"'(.*?)'"|"([^"\s]*)"/g;
const string = `bike "car" bus "'airplane'" "bike" "'train'"`;
const result = string.replace(regex, (_, g1, g2) => g1 ? `'${g1}'` : `'${g2}'`);
console.log(result);

Answer №2

The @The fourth bird answer is excellent when utilizing a callback for the replace function. Here's an alternative approach that involves two consecutive replaces without the need for callbacks:

const str = `bike "car" bus "'airplane'" "bike" "'train'"`;
let result = str.replace(/"'(.*?)'"/g, "'$1'").replace(/"([^"\s]*)"/g, "'$1'");
console.log(result);

Output:

bike 'car' bus 'airplane' 'bike' 'train'

Explanation:

  • search 1: /"'(.*?)'"/ - matches non-greedy pattern of "'...'"
    • replacement: "'$1'" - substitutes with single quotes
  • search 2: /"([^"\s]*)"/ - scans non-greedy pattern of "..."
    • replacement: "'$1'" - replaces with single quotes

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

Upon initial loading, the default sidenav in Angular is not selected

I need to ensure that the sidenav loads the basic page during the initial load. This is controlled by the routing.ts file shown below: import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; i ...

Using Firebase orderByChild to access a nested object in the database

In my current project, I am utilizing a real-time database with the following data structure: { "users": { "1234": { "name": "Joe", "externalId": "384738473847", }, ...

Setting up Typescript with React 17 and Tailwind CSS version 2.0

I'm struggling to set up TailwindCSS 2.0 with the create-react-app --template typescript configuration and encountering errors. Even after following the instructions on the official TailwindCSS website for React at https://tailwindcss.com/docs/guides/ ...

Error message: The attempted import failed because ' is not exported from the module

I am facing an issue with resolving my problem. In a file named lama.d.ts, I have declared a class using the following code: export declare class lama { // code here } After that, I tried to import this class in another file within the same folder ...

The issue of footer overlapping the login form is observed on iOS devices while using Safari and Chrome

Unique ImageI am currently working on an Angular 8 project with Angular Material. I have successfully designed a fully functional login page. However, I am encountering a problem specifically on iOS devices such as iPhones and iPads, whether it is Safari o ...

A guide on retrieving data from Firestore using TypeScript

I've been diving into a chat project using Angular, and Firestore has given me a bit of trouble. Trying to get the hang of typescript while working with it. Within app.module.ts, kicking things off with: import { provideFirebaseApp, getApp, initi ...

Accessing Properties or Methods in Angular2 Components

My application consists of 3 main components: PageMenu, LoginSession, and LoginForm. The purpose is to establish a connection between the variables in LoginSession and PageMenu, allowing for the proper functionality of the LoginForm component. PageMenu: ...

Leverage server-side data processing capabilities in NuxtJS

I am currently in the process of creating a session cookie for my user. To do this, I send a request to my backend API with the hope of receiving a token in return. Once I have obtained this token, I need to store it in a cookie to establish the user' ...

I'm having trouble inputting text into my applications using React.js and TypeScript

I am encountering an issue where I am unable to enter text in the input fields even though my code seems correct. Can anyone help me figure out what might be causing this problem? Below is the code snippet that I am referring to: const Login: SFC<LoginP ...

Verifying the URL to determine if it includes the specific string needed to modify the Jade theme in

I am currently exploring ways to check if a URL string is present in an express application, in order to initiate a theme change. At the moment, I have a basic router.get function: router.get('/', function(req, res, next) { res.render(' ...

Looking to retrieve a single data point from [object][object]

Presented here is an angular component: import { Component, OnInit } from '@angular/core'; import { Hall } from 'src/app/models/hall.model'; import { HallService } from 'src/app/services/hall.service'; import { ActivatedRoute, ...

Unit testing of an expired JWT token fails due to the incorrect setting of the "options.expiresIn" parameter, as the payload already contains an "exp" property

I am having trouble generating an expired JWT token for testing purposes and need some guidance on how to approach it. How do you handle expiration times in unit tests? This is what I have attempted so far : it('should return a new token if expired& ...

formik connects props that are lacking certain properties

Trying to figure out a way to simplify the process of declaring all the properties of formik in my Props when using connect(). The error message I keep encountering is: Type '{ entry: Entry; }' is missing the following properties from type &apos ...

What is the best way to eliminate a specific set of characters from a string using TypeScript?

Imagine you have the following lines of code stored in a string variable: let images='<img alt="image1" height="200" src="image1.jpg" width="800"> <img alt="image2" src="image2.jpg" height="501" width="1233"> <img alt="im ...

Extracting Object Properties from Arrays in TypeScript

Code Snippet: interface Human { name: string; age: number; } interface Pet { name: string; type: string; } If I have an array of Human, how can I get an array of Pet's type. For instance: Is there a built-in way to achieve this in typescr ...

Break down and extract elements using typedEvent in TypeScript

Within the external library, there is the following structure: export interface Event extends Log { args?: Result; } export interface TypedEvent<EventArgs extends Result> extends Event { args: EventArgs; } export type InstallationPreparedEven ...

Assign a dynamic class to an element within an ngFor iteration

I am working with a template that includes an app-subscriber component being iterated over using *ngFor: <app-subscriber *ngFor="let stream of streams" [stream]="stream" [session]="session" (speakEvents)='onSpeakEvent($event)'> ...

It is not possible to access the Angular component using routing capabilities

I'm facing an issue with my Angular routing setup. I have two components, "view-emp" and "edit-emp", but only "edit-emp" is accessible for navigation. When I try to click on the link to navigate to "view-emp", nothing happens and I stay on the home sc ...

Combining subclasses in TypeScript

Do you need help with a tricky situation? ...

Typescript is failing to compile classes in a reliable sequential order

In my MVC 5 project, I am using TypeScript and angular. There are three TS files: Controller1.ts, Controller2.ts, and app.ts. The issue arises when I compile the program for the first time - everything usually compiles correctly in the expected order. Howe ...