I want to get the file endings from some files in a list.
File 1
File 2
File 3
File 4
Basically, the file endning could be anything, and the string can contain more than just one ".". So I need to fetch the ending only.
I want to get a result that looks like:
mp4
ogg
mp3
jpg
Thanks.
You can get the extensions for all links in a document like this:
var endings = [];
var links = document.getElementsByTagName("a");
var matches;
for (var i = 0; i < links.length; i++) {
if (links[i].href) {
matches = links[i].href.match(/\.([^\.]+)$/);
if (matches) {
endings.push(matches[1]);
}
}
}
// the array endings contains a list of all link extensions
Here's a working version of the code: http://jsfiddle.net/jfriend00/XHKaT/
The regular expression here matches a period followed by one or more non-period characters at the end of the string. The parenthesized grouping allows us to extra just the extension without the period which accomplishes the result you outlined.
This function performs as you need without reporting duplicates and maintaining the order in which the filename extensions are discovered.
function getLinkedFileExtensions() {
var i, len=document.links.length, ext=[], exts={};
for (i=0; i<len; i++) {
var a = document.links[i];
if (a.href && a.href.match(/\.([A-Za-z0-9]{1,4})$/)) {
var x = RegExp.$1;
if (!(x in exts)) {
exts[x] = true;
ext.push(x);
}
}
}
return ext;
}
var ext = [].map.call(document.links, function (a) {
return (a.href.match(this) || [])[1] || "";
}, /\.([a-zA-Z0-9]*)$/).filter(String);
http://jsfiddle.net/hZ9cU/
You can use jQuery to:
Get all of your anchor elements.
For each element you can access the .attr("href") value which will be your address string i.e. "myfile.mp3"
Then you can split the string on "." character and add the value at tokenArray[tokenArray.length-1] to your result list.
Or for vanilla JS try:
function getExtensions(){
var allAnchorTags = document.getElementsByTagName("a");
var extensions = new Array();
for(var i = 0; i < allAnchorTags.length; i++){
var tokenArray = allAnchorTags[i].href.split(".");
extensions[i] = tokenArray[tokenArray.length-1];
}
return extensions;
}
which does the same as described in my algorithm except with vanilla JS syntax. Give it a shot
See Feedle
var ext = a.href.split(".");
ext = ext[ext.length -1];
console.log(ext);
EDIT :
var d = document.getElementsByTagName("a"),
ext, i, j;
for(i = 0, j = d.length; i<j; i++){
ext = d[i].href.split(".");
ext = ext[ext.length -1];
console.log(ext);
}
Related
I try to make a javascript code for ImageJ, wich have to goal to allow me to select a directory, and return me all jpg and jpeg file in the directory and sub-directory.
I have do this code, it's work well for direct children, he call well getJpeg on subdirectories (I have verify it with some IJ.log), but the jpeg Array is not concat with result of recursives call
Have you an idea?
importClass(Packages.ij.IJ);
importClass(Packages.ij.plugin.frame.RoiManager);
importClass(Packages.ij.gui.GenericDialog);
importClass(Packages.ij.io.OpenDialog);
importClass(Packages.java.io.File);
var dirstr = IJ.getDirectory("Choose the stacks folder");
var jpeg = getJpeg(dirstr);
for (var i = 0; i < jpeg.length; i++) {
IJ.log(jpeg[i]);
}
function getJpeg(dirst) {
var dir = new java.io.File(dirst);
var names = dir.listFiles();
var jpeg = new Array();
for (var i = 0 ; i < names.length; i++) {
if(names[i].isDirectory()){
jpeg.concat(getJpeg(names[i].getPath()));
continue;
}
var namest = names[i].getName();
if (namest.match(/.*\.jpg|jpeg/)) {
var path = names[i].getPath();
jpeg.push(path);
}
}
return jpeg;
}
Thank you :)
The problem come from a missread from concat documentation ( w3schools.com/jsreF/jsref_concat_array.asp ). Have to put
jpeg = jpeg.concat(getJpeg(names[i].getPath()));
Looking for some help with Javascript in Adobe Acrobat Pro XI.
Here's what I have so far:
/* Extract pages to file */
// Regular expression used to acquire the base name of file
var re = /\.pdf$/i;
// filename is the base name of the file Acrobat is working on
var filename = this.documentFileName.replace(re,"");
try {for (var i = 0; i < this.numPages; i+=4)
this.extractPages({
nStart: i,
nEnd: i+3,
});
} catch (e) { console.println("Aborted: " + e) }
What happens now is that it extracts the page range and creates a series of open files that I can then rename.
What I'd like to do is add a loop to extract a name from the bill, then use that as the file name to create a new file in a folder.
I found this:
for (var p = 0; p < this.numPages; p++) {
// iterate over all words
for (var n = 0; n < this.getPageNumWords(p); n++) {
if (this.getPageNthWord(p, n) == stringToSearchFor) {
pageArray.push(p);
break;
}
}
}
which I think will get me part of the way there, but I'm not sure how to include that in my loop.
I think I need to search the document a static string (in this case "Student Name") and then return the next two words.
Worked up a file to do this sort of thing using copy-pasted code (and some help from Thom Parker on the Adobe Forums, see: https://community.adobe.com/t5/acrobat/step-by-step-instructions-for-saving-a-pdf-in-acrobat-dc-using-a-javascript/m-p/10893916?page=1#M238905)
// https://community.adobe.com/t5/acrobat/how-to-set-up-a-default-value-in-execdialog/td-p/9343585?page=1
var dialogTitle = "Please specify ";
var defaultAnswer = "";
var stringToSearchFor = app.response("Client ID",
dialogTitle, defaultAnswer);
//https://acrobatusers.com/tutorials/print/how-save-pdf-acrobat-javascript/
/* Put script title here */
// Iterates over all pages and find a given string and extracts all
// pages on which that string is found to a new file.
var pageArray = [];
//var stringToSearchFor = "64718";
for (var p = 0; p < this.numPages; p++) {
// iterate over all words
for (var n = 0; n < this.getPageNumWords(p); n++) {
if (this.getPageNthWord(p, n) == stringToSearchFor) {
pageArray.push(p);
break;
}
}
}
if (pageArray.length > 0) {
// extract all pages that contain the string into a new document
var d = app.newDoc(); // this will add a blank page - we need to remove that once we are done
for (var n = 0; n < pageArray.length; n++) {
d.insertPages( {
nPage: d.numPages-1,
cPath: this.path,
nStart: pageArray[n],
nEnd: pageArray[n],
} );
}
// remove the first page
d.deletePages(0);
// https://community.adobe.com/t5/acrobat/how-to-save-as-pdf-form-using-script/td-p/9848947?page=1
// Split Path into an array so it is easy to work with
var aMyPath = this.path.split("/");
// Remove old file name
aMyPath.pop();
// Add new file name
aMyPath.push(stringToSearchFor);
// Put path back together and save
d.saveAs(aMyPath.join("/")+".pdf");
}
I have a gigantic list (800 items) and one really long string. I want to get the first item in the array that matches the part of the string and stored in a variable.
My code currently:
for (var i = 0; i<gigantic_genre_array.length; i++) {
var test_genre = thelongstr.indexOf(gigantic_genre_array[i]);
if(test_genre != -1) {
tag1 = gigantic_genre_array[test_genre];
alert(tag1);
}
}
This doesn't work like I thought it would, any suggestions?
Try this:
for(var i = 0; i<gigantic_genre_array.length; i++){
var test_genre = thelongstr.indexOf(gigantic_genre_array[i]);
if(test_genre!=-1){
tag1 = gigantic_genre_array[i];
alert(tag1);
}
}
Do the process reversely it will be efficient too.
var wordArray = thelongstr.split(' ');
for(var i=0,len = wordArray.length; i < len; i++)
{
if(gigantic_genre_array.indexOf(wordArray[i]) > -1)
{
alert(wordArray[i]);
}
}
You may create a RegExp based on the array and test it against the string:
var gigantic_genre_array=['foo','bar','foobar'];
var thelongstr='where is the next bar';
alert(new RegExp(gigantic_genre_array.join('|')).exec(thelongstr)||[null][0]);
//returns bar
I'm attempting to teach myself javascript. I chose something I assumed was simple, but ran into problems relatively quickly.
I'm attempting to search a string for another string given by the user.
My code so far is:
var source = "XREs2qqAQfjr6NZs6H5wkZdOES5mikexRkOPsj6grQiYNZfFoqXI4Nnc1iONKVrA";
var searchString = []; //the users input
searchString = prompt("Enter search string");
var hits = [];
var one = 0;
var two = 0;
var k = 0;
var sourceSearch = function(text) {
for(i = 0; i < source.length; i++) { //for each character in the source
if(source[i] === searchString[0]) { //if a character in source matches the first element in the users input
one = source.indexOf(i); //confused from here on
for(p = searchString.length; p > 0; p--) {
}
}
}
};
sourceSearch(searchString);
My idea was:
check to see if the first loop finds a character that matches the first character in the user input
if it matches, check to see if the next X characters after the first match the next X characters in the source string
if they all match, push them to the hits array
My problem: I have no idea how to iterate along the arrays without nesting quite a few if statements, and even then, that wouldn't be sufficient, considering I want the program to work with any input.
Any ideas would be helpful. Thanks very much in advance.
Note: There are a few un-used variables from ideas I was testing, but I couldn't make them work.
You can try:
if (source.indexOf(searchString) !== -1) {
// Match!
}
else
{
//No Match!
}
As the other answers so far point out, JavaScript strings have an indexOf function that does what you want. If you want to see how it's done "by hand", you can modify your function like this:
var sourceSearch = function(text) {
var i, j, ok; // always declare your local variables. globals are evil!
// for each start position
for(i = 0; i < source.length; i++) {
ok = true;
// check for a match
for (j = searchString.length - 1; ok && j >= 0; --j) {
ok = source[i + j] === searchString[j];
}
if (ok) {
// searchString found starting at index i in source
}
}
};
This function will find all positions in source at which searchString was found. (Of course, you could break out of the loop on the first success.) The logic is to use the outer loop to advance to each candidate start position in source and use the inner loop to test whether that position actually is the position of a match to searchString.
This is not the best algorithm for searching strings. The built-in algorithm is much faster (both because it is a better algorithm and because it is native code).
to follow your approach, you can just play with 2 indexes:
var sourceSearch = function(text) {
j = 0;
for(i = 0; i < source.length; i++) {
if(source[i] === text[j]) {
j++;
} else {
j = 0;
}
if (j == text.length) {
console.log(i - j); //this prints the starting index of the matching substring
}
}
};
These answers are all pretty good, but I'd probably opt for something like this:
var source = "XREs2qqAQfjr6NZs6H5wkZdOES5mikexRkOPsj6grQiYNZfFoqXI4Nnc1iONKVrA";
var searchString = []; //the users input
searchString = prompt("Enter search string");
var hits = source.split(searchString);
var hitsCount = hits.length - 1;
This way you have all of the data you need to figure out where each hit occurred in he source, if that's important to you.
I want to code a check for duplicate url's, but a simple string match will not work, e.g. string1 == string2. Consider the following url's as an example:
www.facebook.com/authorProfile
facebook.com/authorProfile
http://www.facebook.com/authorProfile
http://facebook.com/authorProfile
function extract(str){
var patterns = [
"http://www.",
"http://",
"www."
];
for(var i=0, len=patterns.length; i < len; i++){
var pattern = patterns[i];
if(str.indexOf(pattern) == 0)
return str.substring(pattern.length);
}
return str;
}
This will convert all those links to facebook.com/authorProfile style so you can compare them.
links = [
"www.facebook.com/authorProfile",
"facebook.com/authorProfile",
"http://www.facebook.com/authorProfile",
"http://facebook.com/authorProfile"
];
for(var i=0, len=links.length; i<len; i++){
console.log( extract(links[i]) );
}
// will produce 4 "facebook.com/authorProfile"
How about using javascript regex? Basically, remove http:// and www.
.replace(/www.|http:\/\//g, '');
Example:
var s1 = 'www.facebook.com/authorProfile';
var s2 = 'facebook.com/authorProfile';
var s3 = 'http://www.facebook.com/authorProfile';
var s4 = 'http://facebook.com/authorProfile';
s1.replace(/www.|http:\/\//g, '');
s2.replace(/www.|http:\/\//g, '');
s3.replace(/www.|http:\/\//g, '');
s4.replace(/www.|http:\/\//g, '');
All become:
facebook.com/authorProfile