本文介绍了字符串操作,以删除最后一次出现的字符“".的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到的情况是,如果给定的字符串的引号是奇数的" ,则最后一个引号必须替换为空字符串.这是我遵循的方法来实现的代码,但是它不能替换字符串,任何人都可以帮我吗?

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

提前感谢:)

推荐答案

尝试如下:

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

当调用 evenOrOdd 函数时,需要提供出现次数,然后检查结果是"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.

这篇关于字符串操作,以删除最后一次出现的字符“".的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 12:04