Results 1 to 2 of 2

Thread: javascript string trimming

  1. #1
    Join Date
    Sep 2009
    Posts
    4
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default javascript string trimming

    i am wanting to make a javascript function that when a link is clicked it runs a function. that function will then take the content of a text box start at the end of the textbox and remove all the text up till the first "/" it comes to. so if you have in the textbox: c:/program files/new folder, after the script is finished it will look like: c:/program files/
    i know how to get the contents from the textbox and everything else i just need help on the trimming of the string. any help will be most appreciated

  2. #2
    Join Date
    Mar 2005
    Location
    SE PA USA
    Posts
    30,495
    Thanks
    82
    Thanked 3,449 Times in 3,410 Posts
    Blog Entries
    12

    Default

    Assuming (as I believe you've indicated) that you know how to both get and set the value of the text box and/or do whatever it is you want to do with the value of the text box - say the value of the text box is now in a declared var named str:

    Code:
    str = str.replace(/\/[^\/]*$/, '/');
    ex:

    Code:
    var str = 'c:/program files/new folder';
    str = str.replace(/\/[^\/]*$/, '/');
    alert(str);
    The above will alert:

    Code:
    c:/program files/
    Edit:
    There is another way:

    Code:
    var str = 'c:/program files/new folder';
    str = str.substring(0, str.lastIndexOf('/') + 1);
    alert(str);
    Same result. However, there is a difference. With the first method if there is no / in the string, the entire string will be preserved. Using the second method, if there is no /, you will be left with an empty string. So if that matters, pick the one that best suits your purposes.
    Last edited by jscheuer1; 10-15-2009 at 06:40 AM. Reason: add info
    - John
    ________________________

    Show Additional Thanks: International Rescue Committee - Donate or: The Ocean Conservancy - Donate or: PayPal - Donate

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
  •