Trim the End of a String in JavaScript with ES2019 trimEnd

Mike Sherov
InstructorMike Sherov
Share this video with your friends

Social Share Links

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.

Instructor: [00:01] Once again, we're looking at our Nuxt application. This time, we want to see how we can print out the students' teachers. The first thing we'll notice, though, is that in the input data, there is some incorrect spacing with respect to the commas.

[00:14] Alicia's teacher is Jim and Bob, and there should be no space between Jim and the trailing comma after his name. We can see in our output that, in fact, we've fixed this bug.

[00:27] We can see that the way that we have done this is, when transforming records, we would take the students' teachers and split the string by a comma, which will turn it into an array of the teachers' names, spaces and all.

[00:40] Then mapping the teachers' names to trim white space from before and after their name. Then add white space again before their name, and then join them again with a comma.

[00:52] The way this looks is, it takes something like "Jim Bob" and then maps it, and splits it an array of "Jim , Bob", and then maps over that array, trimming the white space from the front and back, and adding white space to the front, giving us Jim, Bob like that.

[01:22] Finally, joining them with a comma in-between. What we end up with is the string " Jim, Bob". We can see, if we look at a JSON representation of our teachers, even though we have managed to remove that space in-between the comma and Jim's name, we've now got an erroneous space in front.

[01:44] The problem here is, we only want to trim off white space from the right-hand side of Jim's name, rather than trimming white space off of both sides and then adding a space to the front. Thankfully, in ES2019, this couldn't be simpler.

[01:58] The function now exists called trimEnd, and we could, instead of having to add the white space, just call trimEnd, save again, and we'll see that it's now Jim and Bob, with no preceding space.