treehouse : what would you like to learn today?
Web Design Web Development iOS Development

Trim First/Last Characters in String

Last updated on:

Remove last four characters

var myString = "abcdefg";
var newString = myString.substr(0, myString.length-4); 
// newString is now "abc"

Remove first two characters

var myString = "abcdefg";
var newString = myString_2.substr(2);
// newString is now "cdefg"

Notes

The substr function can be called on any string with two integer parameters, the second optional. If only one provided, it starts at that integer and moves to the end of the string, chopping off the start. If two parameters provided, it starts at the first number and ends at the second, chopping off the start and end as it is able.

Example

abcdefghijklmnopqrstuvwxyz

View Comments

Comments

  1. Joshua
    Permalink to comment#

    The snippet on this page isn’t working for me, and is throwing the following error:

    $(‘#chopper’)[0].innerText is undefined

    Just a heads up!

  2. Pauly

    i already try to click the button ” Press to chop” but nothing happen, how come?

  3. Permalink to comment#

    I think the code snippet for the second example has a typo:
    var myString = “abcdefg”;
    var newString = myString_2.substr(2);

    The second line of this snippet should be:
    var newString = myString.substr(2);

    Thanks for the tip!

Leave a Comment

Use markdown or basic HTML and be nice.