View Full Version : javascript string trimming

10-14-2009, 07:27 PM
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:)

10-15-2009, 02:26 AM
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:

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


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

The above will alert:

c:/program files/

There is another way:

var str = 'c:/program files/new folder';
str = str.substring(0, str.lastIndexOf('/') + 1);

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.