Trim the End of a String in JavaScript with ES2019 trimEnd

Share this video with your friends

Send Tweet

ES2019 introduces the String.prototype.trimEnd and String.prototype.trimStart methods. In this lesson, we'll investigate a common use case for .trimEnd. We'll figure out how to work around the lack of .trimEnd in older versions of JS, and then refactor the code to use .trimEnd to achieve an even better result with less complexity.

Ya Zhuang
Ya Zhuang
~ 5 years ago

why not just join(', ') LOL

Mike Sherov
Mike Sherov(instructor)
~ 5 years ago

Hi Ya,

Thanks for the question! Yeah, you could absolutely do that. To be honest, I found it hard to find a good real world example here. I figured the use case was good enough to illustrate the functionality. :shrug:

Cory Kleiser
Cory Kleiser
~ 5 years ago

Mentioning that String.prototype.trimStart exists as well would be good.

AlexanderS Sadovsky
AlexanderS Sadovsky
~ 5 years ago

My solution would be x.replace(/ ,/g, ',');

Ryan
Ryan
~ 5 years ago

I think to use join(', ') is more simple solution.

J. Matthew
J. Matthew
~ 5 years ago

[...] Yeah, you could absolutely do that. To be honest, I found it hard to find a good real world example here. I figured the use case was good enough to illustrate the functionality. :shrug:

These two new string methods remind my of my early coding days, when I would try to offer the most complete functionality possible, without asking whether it would be used. I'm curious whether there were people asking for these methods, and if so, what their example use-cases were. I, too, struggle to come up with any situation where you'd want to preserve the white space on either end of a string, especially when there's no guarantee that it would be consistent.