80

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!

4 Answers 4

144

Use a simple regular expression:

var s = "item,";
s = s.replace(/,+$/, "");
Sign up to request clarification or add additional context in comments.

2 Comments

Just wanted to add: don't forget the backslash if you're replacing characters that have meanings to regular expressions (for example, '.').
Just so you know, this is vulnerable to ReDoS. devina.io/redos-checker
22
if(myStr.charAt( myStr.length-1 ) == ",") {
    myStr = myStr.slice(0, -1)
}

5 Comments

That if should probably be a while.
Ummmm why?? If the last character is a comma, slice the last character... I mean the most probable use case for this, is when you get an element from an array and make a JSON-ish text or something. You go like 'foreach element print element and ","' but then you realize, "dude, i have an extra ','" and wanna remove it.
He says ","s in plural, but I agree the title is confusing.
Yeah I think it depends on what he wants to achieve. @Dutrow pls explain
It doesn't hurt to use a while, It's really unlikely that his specific need involved not stripping a trailing comma.
15

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

2 Comments

How would it perfom on '///te/st//,'/' ?
@TomasHesse - seems to work! I added a snippet above to test it out
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.