Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove trailing character(s) from string in Javascript

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!

like image 299
Chris Dutrow Avatar asked Apr 25 '11 00:04

Chris Dutrow


People also ask

How do you remove trailing from strings?

To remove leading and trailing spaces in Java, use the trim() method. This method returns a copy of this string with leading and trailing white space removed, or this string if it has no leading or trailing white space.

How do I remove a character from the end of a string in JavaScript?

To remove the last character from a string in JavaScript, you should use the slice() method. It takes two arguments: the start index and the end index. slice() supports negative indexing, which means that slice(0, -1) is equivalent to slice(0, str. length - 1) .

How do you trim a character in JavaScript?

JavaScript provides three functions for performing various types of string trimming. The first, trimLeft() , strips characters from the beginning of the string. The second, trimRight() , removes characters from the end of the string. The final function, trim() , removes characters from both ends.


Video Answer


1 Answers

Use a simple regular expression:

var s = "item,"; s = s.replace(/,+$/, ""); 
like image 123
Tim Down Avatar answered Oct 14 '22 16:10

Tim Down