Removing last character in a string

How do you remove the last character in a dynamic string?

I have been trying substr(), however, I can only get this function to remove characters from the beginning of the string and not the end. (I need to do both)


// this variable will be dynamic and has a "?" and "/" added
var mp3_track = "?http://www.website.com/song.mp3/"

// removed the first character
mp3_track.substr(1)

// How to I remove the last?


I’m sure this is an easy one for you JS guru’s :slight_smile:

var foo = mp3_track.substring(0, mp3_track.length - 1);

To remove the last character from a string you can use a regexp-

var str= mp3_track.replace(/.$/,‘’)

To remove characters from BOTH the beginning and the end of a string use slice-

var str=mp3_track.slice(1,-1)

You could just use negative values but if you cater to IE then you’re in trouble. :slight_smile:

  
<script type="text/javascript">
var mp3_track = "?http://www.website.com/song.mp3/"
var str=mp3_track.replace(/^.|.$/g,"");
alert(str);  // http://www.website.com/song.mp3
</script>

Thanks everyone. This option was the simplest and works fine.