String Manipulation to remove last occurrence of a character `"`

Viewed 609

I have situation where if the given string has odd number of quotation mark " then the last quotation mark has to be replaced with empty string. Here is my code I have followed an approach to achieve that but it is not replacing the string can anyone please help me out ?

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 :)

2 Answers

You can replace like below:

const input = `"hello,"sai,sur",ya,teja`;
const idx = input.lastIndexOf('"');
const result = input.substr(0, idx) + input.substr(idx+1)


console.log(result);

Try like this:

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

let output = "";
let lastIndex = null;

if (evenOrOdd(input.split(`"`).length - 1) === "odd") {
  //Here the last occurrence which needed to be replaced with empty string
  lastIndex = input.lastIndexOf(`"`)
  output = input.substring(0, lastIndex) + input.substring(lastIndex + 1)
}

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";
  }
}

When calling the evenOrOdd function, the number of occurences needs to be provided, then the result is checked to be either "odd" or "even". If it's even, then we're done. We only want to replace the last occurrence if it's odd. We can simply do this by position (index) within the string. Replacing with the Regex afterwards doesn't seem to be needed.

Related