Remove trailing character(s) from string in Javasc

2020-02-19 01:02发布

What is an acceptable way to remove a particular trailing character from a string?

For example if I had a string:

> "item,"

And I wanted to remove trailing ','s only if they were ','s?

Thanks!

3条回答
Summer. ? 凉城
2楼-- · 2020-02-19 01:41
if(myStr.charAt( myStr.length-1 ) == ",") {
    myStr = myStr.slice(0, -1)
}
查看更多
我只想做你的唯一
3楼-- · 2020-02-19 01:58

Use a simple regular expression:

var s = "item,";
s = s.replace(/,+$/, "");
查看更多
爷的心禁止访问
4楼-- · 2020-02-19 01:58

A function to trim any trailing characters would be:

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

查看更多
登录 后发表回答