正则表达式-从Javascript中的字符串中删除结尾字符

从字符串中删除特定结尾字符的可接受方法是什么?

例如,如果我有一个字符串:

> "item,"

而且我想删除尾随的“,”,前提是它们是“,”?

谢谢!

Chris Dutrow asked 2020-01-24T05:44:02Z
3个解决方案
100 votes

使用简单的正则表达式:

var s = "item,";
s = s.replace(/,+$/, "");
Tim Down answered 2020-01-24T06:02:12Z
14 votes
if(myStr.charAt( myStr.length-1 ) == ",") {
    myStr = myStr.slice(0, -1)
}
Vicente Plata answered 2020-01-24T06:02:28Z
8 votes

修剪任何结尾字符的功能是:

function trimTrailingChars(s, charToTrim) {
  var regExp = new RegExp(charToTrim + "+$");
  var result = s.replace(regExp, "");

  return result;
}

function test(input, charToTrim) {
  var output = trimTrailingChars(input, charToTrim);
  console.log('input:\n' + input);
  console.log('output:\n' + output);
  console.log('\n');
}

test('test////', '/');
test('///te/st//', '/');

Brad Parks answered 2020-01-24T06:02:53Z
translate from https://stackoverflow.com:/questions/5774246/remove-trailing-characters-from-string-in-javascript