[英]How to remove/replace first occurrence of character from the right using JavaScript dynamic approach?
example例子
var string = "ACABBCAA";
var a = "A";
var b = "B";
var c= "C";
output:输出:
removeLastChar(string,a); //output ACABBCA
removeLastChar(string,b); //output ACABCAA
removeLastChar(string,c); //output ACABBAA
What I have tried so far?到目前为止我尝试过什么?
Solution 1解决方案1
function removeLastChar(string,char){
result = string.replace(new RegExp('/'+char+'$/'), "");
return result;
}
Solution 2解决方案2
function removeLastChar(string,char){
result = string.replace('/'+char+'$/', "");
return result;
}
I already asked in the comments here but not working out.我已经在这里的评论中问过,但没有解决。
This is my way to do it这是我的方法
var text = "ACABBCAA";
var a = "A";
var b = "B";
var c= "C";
function removeLastChar(string,char){
let charLastPosition = string.lastIndexOf(char);
let newString = string.substring(0, charLastPosition) + string.substring(charLastPosition + 1);
return newString;
}
document.write(removeLastChar(text, a));
if you wanna replace you can do it un this way.如果你想更换,你可以这样做。
var text = "Notion,Data,Identity,";
var a = "A";
var b = "B";
var c= "C";
function replaceLastChar(string,char, charToReplace){
let charLastPosition = string.lastIndexOf(char);
let newString = string.substring(0, charLastPosition) + charToReplace + string.substring(charLastPosition + 1);
return newString;
}
document.write(replaceLastChar(text, ',', '.'));
Use lastIndexOf
and splice
with spread notation ...
.使用lastIndexOf
和splice
with spread notation ...
。
function removeLastChar(string, char) {
let strArr = [...string];
strArr.splice(string.lastIndexOf(char), 1);
return strArr.join("");
}
You could use a dynamic regex like this: ${char}(?=[^${char}]*$)
(For B
it would be: B(?=[^B]+$)
).您可以使用这样的动态正则表达式: ${char}(?=[^${char}]*$)
(对于B
将是: B(?=[^B]+$)
)。 This will match the last instace of a character and replace
it with empty string这将匹配字符的最后一个实例并将其replace
为空字符串
function removeLastChar(str, char) { const regex = new RegExp(`${char}(?=[^${char}]*$)`) return str.replace(regex, '') } console.log(removeLastChar("ACABBCAA", "A")); console.log(removeLastChar("ACABBCAA", "B")); console.log(removeLastChar("ACABBCAA", "C"));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.