SitePoint Sponsor

User Tag List

Results 1 to 8 of 8
  1. #1
    SitePoint Member
    Join Date
    Aug 2004
    Location
    US
    Posts
    22
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Help with String Manipulation

    Hello,

    I need to chop up a string to obtain just the filename of an image. Lets say the image source is /images/thumbs/image.jpg. Using the DOM I have the source of the image in a variable called 'source'.

    What I want to do is manipulate it so that it just returns the file name image.jpg. How can I achieve this? I tried split() to see if I could split it into an array using the / as a separator, but this didn't work.

    Thanks.

  2. #2
    SitePoint Addict NikoB's Avatar
    Join Date
    Nov 2005
    Location
    Austria
    Posts
    211
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    try

    string.substring(string.lastIndexOf('/'));
    Corinis OpenSource Community & Content Management
    http://www.corinis.org

  3. #3
    SitePoint Member
    Join Date
    Aug 2004
    Location
    US
    Posts
    22
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks. How do I test to make sure if a '/' is present in the first place? Something like
    if (string.indexOf('/') != -1) ??

    Thanks

  4. #4
    SitePoint Addict NikoB's Avatar
    Join Date
    Nov 2005
    Location
    Austria
    Posts
    211
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    exactly...
    Corinis OpenSource Community & Content Management
    http://www.corinis.org

  5. #5
    SitePoint Member
    Join Date
    Aug 2004
    Location
    US
    Posts
    22
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks. One more thing, how do I remove the '/' in the filename once I strip out all of the other path information?

  6. #6
    SitePoint Addict NikoB's Avatar
    Join Date
    Nov 2005
    Location
    Austria
    Posts
    211
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    if it isnt stripped out anyway (I always forget if substring cuts away the index or before the index), just use lastIndexOf()+1
    Corinis OpenSource Community & Content Management
    http://www.corinis.org

  7. #7
    SitePoint Wizard stereofrog's Avatar
    Join Date
    Apr 2004
    Location
    germany
    Posts
    4,324
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Code:
    source = "/images/thumbs/image.jpg";
    
    // try this 
    alert(source.split("/").pop()) 
    
    // or this
    alert(source.match(/[^\/]+$/)[0])

  8. #8
    SitePoint Member
    Join Date
    Aug 2004
    Location
    US
    Posts
    22
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    NikoB, stereofrog - Thanks!


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
  •