Using string manipulation to eliminate the final instance of a specific character """

Can someone assist me with a situation where I need to replace the last quotation mark in a string if there is an odd number of quotation marks? I tried implementing a solution but it doesn't seem to work. Here's my code:

const input = `"hello,"sai,sur",ya,teja`;
let output = "";
if(evenOrOdd(input.split(`"`) == "even")){
 //Here the last occurrence which needed to be replaced with empty string
 input[input.split(`"`).lastIndexOf(`"`)] = "";
 console.log(input);
  output = input.replace(/"([^"]+)"/g, (_, g) => g.replace(',', '-'))
}else{
 output = input.replace(/"([^"]+)"/g, (_, g) => g.replace(',', '-'))
}


console.log(output);

function evenOrOdd(number){
//check if the number is even
if(number % 2 == 0) {
    console.log("The number is even.");
    
    return "even";
}

// if the number is odd
else {
    console.log("The number is odd.");
    return "odd";
   }
}

Thanks in advance :)

Answer №1

Here is a different approach:

const text = `"hello,"sai,sur",ya,teja`;

let result = "";
let lastPosition = null;

if (checkOddOccurrences(text.split(`"`).length - 1) === "odd") {
  //Identifying the position of the last occurrence to be removed
  lastPosition = text.lastIndexOf(`"`)
  result = text.substring(0, lastPosition) + text.substring(lastPosition + 1)
}

console.log(result);

function checkOddOccurrences(count) {
  if (count % 2 == 0) {
    console.log("The count is even.");
    return "even";
  } else {
    console.log("The count is odd.");
    return "odd";
  }
}

When using the checkOddOccurrences function, pass in the number of occurrences. If the result is "even," no further action is needed. Only when it's "odd," we want to remove the last occurrence by its index in the string. Using Regex for replacement may not be necessary in this case.

Answer №2

To make a replacement, follow these steps:

const text = `"hello,"jai,jon",yes,jill`;
const position = text.lastIndexOf('"');
const updatedText = text.substr(0, position) + text.substr(position+1)


console.log(updatedText);

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

The error message "Element is not defined (Object.<anonymous>)" is occurring in the context of Intro.js-react, React, Next.js, and Tailwind

Here is a code snippet: import { useState } from 'react'; import { Steps } from 'intro.js-react'; export default function Dashboard() { const [stepEnabled, setStepEnabled] = useState(true); const steps = [ { intro: &apos ...

"Experiencing sluggish performance with VSCode while using TypeScript and Styled Components

My experience with vscode's type-checking is frustratingly slow, especially when I am using styled components. I have tried searching for a solution multiple times, but have only come across similar issues on GitHub. I attempted to read and understa ...

How can I utilize Javascript XMLHttpRequest to redirect to a different component in Angular 2?

I am attempting to perform a POST request using XMLHttpRequest and I would like to redirect to another component if the xhr request is successful. Here is the code snippet: import {Component, Inject, Injectable, OnInit} from 'angular2/core' imp ...

Trigger the identical event to be sent to two distinct functions upon the corresponding button click in Angular 2 using Typescript

I recently implemented a service that fetches JSON data and subscribes to two different variables within my component. These variables are then used by two separate drop-down lists to filter the data accordingly. The filtered data is then sent to another s ...

Zod's nativeEnum function verifies the value of an enum

Utilizing a zod schema to validate an object containing an enum field: enum Colour { red: 'Red', blue: 'Blue', } const schema = z.object({ colour: z.nativeEnum(Colour), }); Received data from an API includes color values a ...

Establish the default landing page as the home screen when launching the application

Hey, I'm running into a situation where I need to change the default page of my application upon loading. Is there a way to redirect from the home page to another page when the application loads? Thanks! ...

Differentiating AWS API errors in TypeScript: A guide

How can I write different handlers in TypeScript for ThrottlingException and ExecutionLimitExceeded when starting a StepFunction execution? new StepFunction.startExecution({}, (err, data) => { if (err) { // Need to identify ThrottlingExcepti ...

Sorting an array of numbers in TypeScript using the array sort function

Looking to organize an array based on ID, comparing it with another array of numbers var items:[] = [{ item:{id:1},item:{id:2},item:{id:3},item:{id:4} }] var sorted:[] = [1,3,2,4]; Output: var items:[] = [{ item:{id:1},item:{id:3},item: ...

Reducing SCSS import path in Angular 7

Creating a component that is deeply nested raises the issue of importing shared .scss files with long paths: @import '../../../app.shared.scss'; This hassle doesn't exist when it comes to .ts files, thanks to the configuration in tsconfig. ...

A generic type in TypeScript that allows for partial types to be specified

My goal is to create a type that combines explicit properties with a generic type, where the explicit properties have priority in case of matching keys. I've tried implementing this but encountered an error on a specific line - can anyone clarify why ...

What is the best way to pass a string value instead of an event in Multiselect Material UI?

Greetings, currently utilizing Material UI multi select within a React TypeScript setup. In order to modify the multi select value in the child component, I am passing an event from the parent component. Here is the code for the parent component - import ...

PHP XAMPP and Working with POST Requests

Hello and thank you for taking the time to read this. Encountering an issue when attempting to POST a PDF file to the server: Alert: The size of the POST Content-Length is 9353594 bytes, which exceeds the limit of 8388608 bytes in an unknown location on ...

Bundle Angular library exports along with its corresponding models

I am in the process of developing an angular library for our company's private npm repository. Within this library, I aim to export classes that are utilized (injected via @Input()) in the library components. Here is a sample model: export class AdsT ...

Creating a Docker image for an Angular application with Node.js

Currently, I am attempting to develop an Angular application within a Docker environment and then run it as a container locally using Node.js. I have utilized the following Dockerfile to build the image, however, I am unsure of what might be missing when ...

Having trouble assigning the class property in Angular 5

Upon loading the page, a list of products is retrieved from an external JSON source. Each product in the list has a corresponding BUY button displayed alongside it, with the ID of the respective product assigned to the button. The intention is that when a ...

The form doesn't seem to be functioning properly when I incorporate the formgroup and service within the ngOnInit() method

I implemented the formgroup code in ngOnInit() and also utilized a service in ngOnInit(). However, the asynchronous nature of the form is causing issues. The full code on StackBlitz works when I use dummy JSON data within the constructor. Check out the wor ...

Order by surname in the alphabet

In what way can we organize the data from an array of objects alphabetically by last name when there is no separate property for first and last names, but rather a single property called fullname (see example data below)? If we were to sort the data by la ...

Generating Pulumi Outputs for exporting as an external configuration file

I am currently utilizing Cloudrun in GCP and am interested in summarizing the created APIs with API Gateway. To achieve this, a Swagger/OpenAPI v2 document needs to be generated containing the google-generated URLs for the Cloudrun Services. How can I ext ...

Tips for converting API data to DTO (Data Transfer Object) using TypeScript

Here is an array of vehicles with their details. export const fetchDataFromApi = () => { return [ { vehicleId: 1, vehicleType: 'car', seats: 4, wheelType: 'summer', updatedAt: new Date().toISOString }, { vehicleId: 2, vehic ...

Is it possible to postpone the initiation of an Angular application until a promise is fulfilled

At the moment, my code looks like this: new Loader().load().then(() => { platformBrowserDynamic().bootstrapModule(AppModule); }); The issue lies in the fact that I only need to delay the execution of ngOnInit and any route resolving until a prom ...