我遇到的情况是,如果给定的字符串的引号"
为奇数,则最后一个引号必须替换为空字符串。这是我遵循的方法来实现的代码,但是它不能替换字符串,任何人都可以帮我吗?
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 :)
答案 0 :(得分:2)
您可以如下替换:
const input = `"hello,"sai,sur",ya,teja`;
const idx = input.lastIndexOf('"');
const result = input.substr(0, idx) + input.substr(idx+1)
console.log(result);
答案 1 :(得分:2)
尝试这样:
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"
或"even"
。如果是偶数,那么我们就完成了。我们只想替换最后一次出现的奇数。我们可以简单地通过字符串中的位置(索引)来执行此操作。之后似乎不需要用正则表达式替换。