SitePoint Sponsor

User Tag List

Results 1 to 6 of 6
  1. #1
    SitePoint Member
    Join Date
    Dec 2007
    Location
    NB, Canada
    Posts
    16
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    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)
    Code:
    // 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

  2. #2
    SitePoint Author silver trophybronze trophy

    Join Date
    Nov 2004
    Location
    Ankh-Morpork
    Posts
    12,158
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Code JavaScript:
    var foo = mp3_track.substring(0, mp3_track.length - 1);
    Birnam wood is come to Dunsinane

  3. #3
    SitePoint Guru
    Join Date
    Apr 2006
    Posts
    802
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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)

  4. #4
    SitePoint Addict
    Join Date
    Dec 2007
    Posts
    207
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    You could just use negative values but if you cater to IE then you're in trouble.
    mmj

  5. #5
    SitePoint Addict
    Join Date
    Aug 2006
    Posts
    266
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Code:
      
    <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>
    Bismillahirrahmanirrahîm
    Bizi doğru yola, kendilerine nimet verdiklerinin yoluna ilet; gazaba uğrayanların ve sapıklarınkine değil.

  6. #6
    SitePoint Member
    Join Date
    Dec 2007
    Location
    NB, Canada
    Posts
    16
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by AutisticCuckoo View Post
    Code JavaScript:
    var foo = mp3_track.substring(0, mp3_track.length - 1);
    Thanks everyone. This option was the simplest and works fine.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •