开发者

Determining the presence of a file with JavaScript?

I have folder/file tree generated by JavaScript where the folder and files each have checkbox inputs with paths associated 开发者_如何学Pythonwith them, like:

/var/www/site/user/folder7/ or
/var/www/site/user/folder7/file.txt or
/var/www/site/user/folder7/file.? (? being any file extension)

In the case of these paths I need only

/var/www/site/user/folder7

I know that normally to remove file names one would use something like:

var full_path = node.context.nextElementSibling.value;
var folder_target_path = full_path.substring(0, full_path.lastIndexOf("/"));

However this return either:

/var/www/site/user/folder7 or
/var/www/site/user

I could use the lastIndexOf() method if I could use some regex to find .? and then up to the last '/'; however I am fairly new to javascript and have never used regex in it.

Could you suggest an effecient way to get only the folder and not the file path in all cases?

Regards, Steve


Here's the W3 tutorial on JavaScript and regex:

http://www.w3schools.com/jsref/jsref_obj_regexp.asp


var folder_target_path = full_path.replace(/\/[^\/]*$/, '');

will remove the last / and anything following it. I think you can avoid having to escape the /'s in the pattern by creating a Regexp object from a string.


To get this working completely I need to use the following:

     var full_path = node.context.nextElementSibling.value;
     var folder_target_path;

     var pathRE = /\./;
     if (full_path.match(pathRE)){
        folder_target_path = full_path.replace(/\/[^\/]*$/, '');
     } else {
        folder_target_path = full_path;
     }

This either matches a path that contains . (period to designate file extension start) then remove the file name with full_path.replace(/\/[^\/]*$/, ''); otherwise don't modify the full path.

Thanks to all!

Regards, Steve

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜