Remove trailing character(s) from string in Javascript

JavascriptRegexParsing

Javascript Problem Overview


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!

Javascript Solutions


Solution 1 - Javascript

Use a simple regular expression:

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

Solution 2 - Javascript

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

Solution 3 - Javascript

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionChris DutrowView Question on Stackoverflow
Solution 1 - JavascriptTim DownView Answer on Stackoverflow
Solution 2 - JavascriptVicente PlataView Answer on Stackoverflow
Solution 3 - JavascriptBrad ParksView Answer on Stackoverflow