开发者

Remove trailing character(s) from string in Javascript

开发者 https://www.devze.com 2023-02-28 16:56 出处:网络
What is an acceptable way to remove a particular trailing character from a string? For example if I had a str开发者_高级运维ing:

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

For example if I had a str开发者_高级运维ing:

> "item,"

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

Thanks!


Use a simple regular expression:

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


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


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


This will remove trailing non-alphanumeric characters.

const examples = ["abc", "abc.", "...abc", ".abc1..!@#", "ab12.c"];
examples.forEach(ex => console.log(ex.replace(/\W+$/, "")));

// Output:
abc
abc
...abc
.abc1
ab12.c
0

精彩评论

暂无评论...
验证码 换一张
取 消