Determining the presence of a file with JavaScript? - javascript

I have folder/file tree generated by JavaScript where the folder and files each have checkbox inputs with paths associated with 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

Related

apple .replace() Html element generate by handlebar js

I am wondering if how am i able to change the element data by .replace() if i use handlebar js to generate html elements.
For instance i have this role of p tag which display a row of data by handlebar js:
<p id="pre-region">{{region}}</p>
and the result of it is
1,44
and i 'd like to change it to
1+44
If you haven't had any experience of handlebar js then consider the tag be
<p id="pre-region">1,44</p>
how should i change from 1,44 to 1 +44?
UPDATE 1
Here should be an extersion for my question. I am passing the HTML element inside pre-region into an href in order to update my website by Ajax.
After i have converted all the comma in to "+" the API retrieve special character "&B2" which equal to the symbol "+" and the API goes error.
MYDOMAIN/path/getRegion?token&profileId=111&dataType=all&region=1%2B4
This is how may API looks like at the moment
MYDOMAIN/path/getRegion?token&profileId=111&dataType=all&region=1+4
should be the solution
I haven't had any experience of handlebars.js but from my point of view, you can just put the code just before the </body>:
<script>
var node = document.getElementById('pre-region');
node.innerHTML = node.innerHTML.replace(',', '+');
</script>
I'll check out the handlebars js in case it does not work.
Update:
As you mentioned in the comment, if you need to use it in the HTTP request/URL, you may handle the string using decodeURIComponent(yourstring):
decodeURIComponent('1%2B44'); // you get '1+44'
Read more about decodeURIComponent() method from this. In URL, it should be encoded as region=1%2B44 in your case; while it should be decoded if you want to use it in your JavaScript code or display in the web page.
Update 1
You should encode your string when it's used as a part of parameter of HTTP request. Therefore, it looks good if the URL is:
MYDOMAIN/path/getRegion?token&profileId=111&dataType=all&region=1%2B4
What you need to do is decode the string on your server side. I assume that you are in control of the server side. If you are using Node.js, you can just use decodeURIComponent() method to decode the parameter. If you're using Python or PHP as your server language, it should be something like decodeURIComponent() in that language.
Update 2
The solution above only replace the first occasion of comma to +. To solve that, simply use:
<script>
var node = document.getElementById('pre-region');
node.innerHTML = node.innerHTML.replace(/,/g, '+');
// Regular Expression is used here, 'g' for global search.
</script>
PHP has a replaceAll() method, so we can add that method to String.prototype like below if you want:
<script>
String.prototype.replaceAll = function(search, replacement) {
var target = this;
return target.split(search).join(replacement);
}
// Another method to replace all occasions using `split` and `join`.
</script>
Alright, so this is my first answer ever on stack overflow so I'm alien to this whole thing but here we go:
You could try this code in another js file that runs after handlebars:
var pre = $('#pre-region'); // defines a variabe for the element (same as
// document.getElementById('pre-region'))
var retrievedRegion = pre.innerHTML;
var splitten = retrievedRegion.split(',');
var concatenated = parseInt(split[0]) + parseInt(split[1])
retrievedRegion.innerHTML = "'" + concatenated) + "'";
or using replace():
retrievedRegion.replace(',','+')

Indesign Javascript load a file from serverpath

I have a problem with Indesign.
I have a document, where I want to add a picture programmatically.
This is easy, when I use a picture on my localdrive. But I want to add a picture from a server path like \myserver\pictures\pic.jpg
I tried it like I add a picture from localdrive
var f = new File("\\myserver\pictures\pic.jpg");
imgPicture.place(f, false);
Then the value in f is
//myserver/pictures/pic.jpg
I build a try catch around it. The errorMessage is undefined.
I get the same error, when i use the networkdrive letter, like
/x/pictures/pic.jpg
As i saw in the documentation for the file-object, there is only one string-parameter for the path.
Is there a solution?
On an other forum, I found a thread where someone had the same problem. But he did a dirty way to solved it. He did a fileOpenDialog and pasted the link to the file and then it downloads the file to the temp directory.
I can't do this, because I have on my server about 100,000 pictures.
Thanks for help.
Another issue of yours may be that backslash may be interpreted as escaping character thus resulting in something like : \myserverpicturespic.jpg" So you may need to escape the escaping character like : "\\myserver\pictures\pic.jpg" and then pass this string. Finally, when I have a doubt about a file path, I usually use this bit of code :
var f = File.openDialog();
if ( f ) $.writeln ( f.fsName );
FWIW
Loic
I can not get the value of f with the forward slashes as you do. I tried your code and it works fine for me if I pass the file-path as
var f = new File("//myserver/pictures/pic.jpg");
You could convert you path with .toString().replace(/\/g, '/')
Also try to replace spaces in the filepath with
CS 5.5 OSX 10.9

Javascript regex match doesn't run correctly

okay I give up. Here's my code:
var re = /href="(http.*\.jpg)"/g;
var mp3s = body.match(re);
it finds pictures, but it returns href="http://www.picture.com/smthg.jpg"
instead of returning http://www.picture.com/smthg.jpg
any idea why?
The result from match() is actually an object.
I think you need to access the first element on that object.
For example:
body.match(re)[1]
This is where the actual result is kept.
Shameless self-promotion:
I've written a small guide for me, I can never remember how to use these either. It's here: http://queirozf.com/reminders/javascript-regular-expressions-usage-reminder
try
var re = /(http.*\.jpg)/g;
var mp3s = body.match(re);
since you don't need the href.
You want to match the regular expression, but then return just the portion in brackets.
To do this, call the regular expressions exec method. For example:
var body = 'stuff stuff morestuff href="http://www.picture.com/smthg.jpg" and some more stuff';
var re = /href="(http.*\.jpg)"/g;
var regexResults = re.exec(body);
var mp3s = regexResults[1];
alert(mp3s);
Having given you this answer, I must implore you to find a different way to solve this problem. You cannot parse HTML using regular expressions. No matter how sophisticated your regular expression gets, there will be a legal HTML example which will break it.

Use Regex in Javascript to get the filename in a URL

I'm using JavaScript to try and get the filename from the URL.
I can get it using this:
var fn=window.location.href.match(/([^/])+/g);
alert(fn[fn.length-1]); // get the last element of the array
but is there an easier way to get it (e.g., without having to use fn[fn.length-1]
Thanks!!
Add a $ at the end so you only get the last part:
window.location.href.match(/[^/]+$/g);
Personally, I try to use simple string manipulation for easy tasks like this. It makes for more readable code (for a person not very familiar with RegEx).
var url = window.location.pathname;
var filename = url.substring(url.lastIndexOf('/')+1);
Or simply:
var filename = window.location.pathname.substring(window.location.pathname.lastIndexOf('/')+1);
Additional Information
Not that it matters for something so trivial, but this method is also more performant than RegEx: http://jsperf.com/get-file-name
How about:
window.location.href.match(/\/([^/]+)$/)[1];
you can use .pop() to get the last element of an array;
alert(fn.pop());
There is a jQuery plugin that makes it easy to parse URLs and provide access to their different parts. One of the things it does is return the filename. Here's the plugin on GitHub:
https://github.com/allmarkedup/jQuery-URL-Parser
I would recommend using that and avoid reinventing the wheel. Regular expressions is an area of programming where this is particularly applicable.
I recommend to also remove any '#' or '?' string, so my answer is:
var fn = window.location.href.split('/').pop().replace(/[\#\?].*$/,'');
alert(fn);
split('/').pop() removes the path
replace(/[\#\?].*$/,'') replace '#' or '?' until the end $ by empty string

JavaScript To Strip Page For URL

We have a javascript function we use to track page stats internally. However, the URLs it reports many times include the page numbers for search results pages which we would rather not be reported. The pages that are reports are of the form:
http://www.test.com/directory1/2
http://www.test.com/directory1/subdirectory1/15
http://www.test.com/directory3/1113
Instead we'd like the above reported as:
http://www.test.com/directory1
http://www.test.com/directory1/subdirectory1
http://www.test.com/directory3
Please note that the numbered 'directory' and 'subdirectory' names above are just for example purposes and that the actual subdirectory names are all different, don't necessarily include numbers at the end of the directory name, and can be many levels deep.
Currently our JavaScript function produces these URLs using the code:
var page = location.hostname+document.location.pathname;
I believe we need to use the JavaScript replace function in combination with some regex but I'm at a complete loss as to what that would look like. Any help would be much appreciated!
Thanks in advance!
I think you want this:
var page = location.href.substring(0,location.href.lastIndexOf("/"));
You can use a regex for this:
document.location.pathname.replace(/\/\d+$/, "");
Unlike substring and lastIndexOf solutions, this will strip off the end of the path if it consists of digits only.
What you can do is find the last index of "/" and then use the substring function.
Not sure you need a regex if you're just pulling off the last slash + content.
http://www.w3schools.com/jsref/jsref_lastIndexOf.asp
I'd probably use that to search for the last "/" character, then do a substring from the start of the string to that index.
How about this:
var page = location.split("/");
page.pop();
page = page.join("/");
I would think you need to use the .htaccess with rewrite rules to change the look of the url, however I am still looking to see if this is available to javascript. Will repost when I find out more
EDIT*
the lastIndexOf would only give you the position, therefor you would still need to replace. ex:
var temp = page.substring(page.lastIndexOf("/"),page.length-1);
page = page.replace(temp, "");
unfortunately I'm not that advanced in my coding so there is probably more efficient coding in the other answers. Sorry for any inconveniences with my initial answer.

Categories