-3

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

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

Solution 2

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

I already asked in the comments here but not working out.

halfer
  • 19,824
  • 17
  • 99
  • 186
Sayed Mohd Ali
  • 2,156
  • 3
  • 12
  • 28

3 Answers3

1

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, ',', '.'));
iamousseni
  • 130
  • 1
  • 5
1

Use lastIndexOf and splice with spread notation ....

function removeLastChar(string, char) {
  let strArr = [...string];
  strArr.splice(string.lastIndexOf(char), 1);
  return strArr.join("");
}
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
0

You could use a dynamic regex like this: ${char}(?=[^${char}]*$) (For B it would be: B(?=[^B]+$)). This will match the last instace of a character and replace it with empty string

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"));
adiga
  • 34,372
  • 9
  • 61
  • 83