Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson
1×
Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.

Autoplay

    Trim the End of a String in JavaScript with ES2019 trimEnd

    Mike SherovMike Sherov
    javascriptJavaScript

    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.

    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Discuss

    Discuss

    Transcript

    Transcript

    Instructor: 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.

    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.

    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.

    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.

    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.

    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.

    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.

    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.