Javascript 从Javascript中的字符串中删除尾随字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5774246/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 18:47:21  来源:igfitidea点击:

Remove trailing character(s) from string in Javascript

javascriptregexparsing

提问by Chris Dutrow

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?

我想删除尾随的 ',' 仅当它们是 ','s 时?

Thanks!

谢谢!

回答by Tim Down

Use a simple regular expression:

使用一个简单的正则表达式:

var s = "item,";
s = s.replace(/,+$/, "");

回答by Vicente Plata

if(myStr.charAt( myStr.length-1 ) == ",") {
    myStr = myStr.slice(0, -1)
}

回答by Brad Parks

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