首页 > 解决方案 > 删除最后一次出现的字符`"`的字符串操作

问题描述

我有这样的情况,如果给定的字符串有奇数个引号,"那么最后一个引号必须用空字符串替换。这是我的代码,我遵循了一种方法来实现这一目标,但它没有替换字符串,任何人都可以帮我吗?

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

标签: angulartypescript

解决方案


您可以像下面这样替换:

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


console.log(result);


推荐阅读