Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/427.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用JavaScript动态方法从右侧删除/替换第一个出现的字符?_Javascript_Regex_String - Fatal编程技术网

如何使用JavaScript动态方法从右侧删除/替换第一个出现的字符?

如何使用JavaScript动态方法从右侧删除/替换第一个出现的字符?,javascript,regex,string,Javascript,Regex,String,范例 var string = "ACABBCAA"; var a = "A"; var b = "B"; var c= "C"; 输出: removeLastChar(string,a); //output ACABBCA removeLastChar(string,b); //output ACABCAA removeLastChar(string,c); //output ACABBAA 到目前为止我试过什么 解决方案1 function removeLastChar(stri

范例

var string = "ACABBCAA";
var a = "A";
var b = "B";
var c= "C";
输出:

removeLastChar(string,a);  //output ACABBCA
removeLastChar(string,b);  //output ACABCAA
removeLastChar(string,c);  //output ACABBAA
到目前为止我试过什么

解决方案1

 function removeLastChar(string,char){
        result = string.replace(new RegExp('/'+char+'$/'), "");
        return result;
    }
解决方案2

function removeLastChar(string,char){
    result = string.replace('/'+char+'$/', "");
    return result;
}

我已经问过了,但没有解决问题。

这是我的方法

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));
如果你想替换,你可以用这种方法

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, ',', '.'));

您可以像这样使用动态正则表达式:${char}?=[^${char}]*$对于B,它应该是:B?=[^B]+$。这将匹配字符的最后一段,并将其替换为空字符串

函数removeLastCharstr,char{ const regex=new RegExp`${char}?=[^${char}]*$` 返回str.replaceregex, } console.LOGREMOVELASTCHARACABCAA,A; console.LOGREMOVELASTCHARACABCAA,B; console.LOGREMOVELASTCHARACABCAA,C 使用lastIndexOf和带扩展符号的接头


IMO regexp对于这样的应用来说是过分的problem@Rajesh我已经在变量中存储了大写字母。它不是字母,而是可变的。。请阅读全文,您应该考虑使用@最后面,我如何替换或删除一个字符的最后一个使用ListNoxOf?它只会帮助我在字符串中搜索它,我已经知道characterBegin from而不是一个否定的字符类,为什么不使用一个简单的否定前瞻性呢?@JackBashford这看起来像什么,例如a?
function removeLastChar(string, char) {
  let strArr = [...string];
  strArr.splice(string.lastIndexOf(char), 1);
  return strArr.join("");
}