A Web Design Community curated by Chris Coyier

A little dab'll do ya

Code Snippets

Home » Code Snippets » JavaScript » Trim First/Last Characters in String Submit one!

Trim First/Last Characters in String

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

It's Your Turn

At this moment, you have an awesome opportunity* to be the person your mother always wanted you to be: kind, helpful, and smart. Do that, and we'll give you a big ol' gold star for the day (literally).

Posting tips:
  • You can use basic HTML
  • When posting code, please turn all
    < characters into &lt;
  • If the code is multi-line, use
    <pre><code></code></pre>
Thank you,
--- The Management ---