Javascript Filename function / .html strip - javascript

Good Morning,
I'm using a function I got from another post here:
How to get the file name from a full path using JavaScript?
To return the current filename of a webpage
var url=window.location.pathname;
var filename = url.replace(/^.*[\\\/]/, '');
alert(filename);
and I was curious as to whether it is possible to strip the .html from the end while still using this syntax.

I think the easiest way will be
var filename = url.replace(/^.*[\\\/]/, '').replace(".html", "");

Either specify the extensions you want to manage, to be more restrictive, using:
.replace(/^.*[\/](.*)[.](html|jsp|php)/, '$1');
Either be more generic, using:
.replace(/^.*[\/](.*)[.][a-zA-Z0-9]{2,5}/, '$1');
The second one will allow extensions from 2 chars (e.g. .do) to 5 chars (e.g. .xhtml), which could also contain numbers (e.g. .php3).

You can use a capture clause in replace:
var url=window.location.pathname;
alert(url)
var filename = url.replace(/^.*[\\\/](.*).html$/, '$1');
alert(filename);

Related

Is it possible to get this part of a string

I wonder if it's possible to get this part of a string.
Here is my string:
var string = "www.somesite.com/o/images%2Fc834vePyJ3SFVk2iO4rU0ke1cSa2%2F12391381_10205760647243398_2385261683139818614_n.jpg?alt=media&token=7a692a38-6982-474f-bea5-459c987ae575";
Now I want to be able to grab just this part of the string, the file name:
12391381_10205760647243398_2385261683139818614_n.jpg
I tried:
var result = /[^/]*$/.exec(""+url+"")[0];
, but it will return
user%2Fc834vePyJ3SFVk2iO4rU0ke1cSa2%2F12391381_10205760647243398_2385261683139818614_n.jpg?alt=media&token=4c92c4d7-8979-4478-a63d-ea190bec87cf
My Regex is wrong.
Another this is, the file extension can be .png or jpg so it's not fixed to jpg.
You could use a regex to isolate the part you want :
This works :
var string = "www.somesite.com/o/images%2Fc834vePyJ3SFVk2iO4rU0ke1cSa2%2F12391381_10205760647243398_2385261683139818614_n.jpg?alt=media&token=7a692a38-6982-474f-bea5-459c987ae575";
console.log((string.match(/[A-Za-z0-9_]+.(jpg|png|bmp)/))[0].substring(2));
Note that may have to be adapted depending on how much the URL string changes:
var string = "www.somesite.com/o/images%2Fc834vePyJ3SFVk2iO4rU0ke1cSa2%2F12391381_10205760647243398_2385261683139818614_n.jpg?alt=media&token=7a692a38-6982-474f-bea5-459c987ae575";
var out = string.split('?')[0].split('%2F')[2];
console.log(out); // "12391381_10205760647243398_2385261683139818614_n.jpg"
Assuming, you always have an url, first I would decode the encoded / (%2F) characters via:
var string = "www.somesite.com/o/images%2Fc834vePyJ3SFVk2iO4rU0ke1cSa2%2F12391381_10205760647243398_2385261683139818614_n.jpg?alt=media&token=7a692a38-6982-474f-bea5-459c987ae575";
var decodedUrl = decodeURIComponent(string);
and then use a regex:
decodedUrl.match(/[^/]*(?=[?])/)
Mind, that this regex assumes parameters (the part starting with ?...) are present, so if that's not the case, you might have to alter it to your needs.
If the filename always has a .jpg extension:
var url = decodeURIComponent(string);
var filename = url.substring(url.lastIndexOf("/")+1, url.lastIndexOf(".jpg"))
If not:
url = url.substring(url.lastIndexOf("/")+1)
filename = url.substring(0,url.indexOf("?"))
Looking at the string, it appears that the file name is between the second occurrence of "%2F" and the first occurrence of "?" in the string.
The first step is to get rid of the part of the string before the second "%2F". This can be done by splitting the string at every "%2F" and taking the third element in the resulting array.
var intermediate = string.split("%2F")[2]
Then, we need to get rid of everything after the "?":
var file_name = intermediate.split("?")[0]
This should give you the file name from the URL

Regular expressions ignoring a file extension

I need some help with a regular expression. I have the following 4 file names
heapdump.20160406.214053.18914.0013.phd
heapdump.20160406.214053.18914.0013.phd.gz
javacore.20160406.214053.18914.0002.txt
javacore.20160406.214053.18914.0002.txt.gz
Basically what I need is for my regular expression to ignore the files with the .gz on the end of it. I tried the following but it does not seem to work.
/heapdump.*.phd|javacore.*.txt/i
/heapdump*.phd|javacore*.txt/i
/heapdump.\d+.\d+.\d+.\d+.phd|javacore.\d+.\d+.\d+.\d+.txt/i
Thanks
This will work
(?!.*\.gz$)(^.*$)
Regex Demo
JS Code
var re = /(?!.*\.gz$)(^.*$)/gm;
var str = 'heapdump.20160406.214053.18914.0013.phd\nheapdump.20160406.214053.18914.0013.phd.gz\njavacore.20160406.214053.18914.0002.txt\njavacore.20160406.214053.18914.0002.txt.gz';
var result = str.match(re);
document.writeln(result)
It depends on how much you want the solution to be precise. If you only have phd and txt extensions this will work
/heapdump.*\.(phd|txt)$/
Which means: a string starting with heapdump, followed by whatever, then a dot, then phd or txt, end of line
Or you can simply negate a string that ends with dot gz
/.*\.gz$/
One option which does not require using a regular expression would be to split the filename on period (.) into an array, and then check if the last element of the array contains the extension gz:
var filename = "heapdump.20160406.214053.18914.0013.phd.gz";
var parts = filename.split(".");
if (parts[parts.length - 1] == 'gz') {
alert("ignore this file");
}
else {
alert("pay attention to this file");
}

Regex to detect a string that contains a URL or file extension

I'm trying to create a small script that detects whether the string input is either:
1) a URL (which will hold a filename): 'http://ajax.googleapis.com/html5shiv.js'
2) just a filename: 'html5shiv.js'
So far I've found this but I think it just checks the URL and file extension. Is there an easy way to make it so it uses an 'or' check? I'm not very experienced with RegExp.
var myRegExp = /[^\\]*\.(\w+)$/i;
Thank you in advance.
How bout this regex?
(\.js)$
it checks the end of the line if it has a .js on it.
$ denotes end of line.
tested here.
Basically, to use 'OR' in regex, simply use the 'pipe' delimiter.
(aaa|bbb)
will match
aaa
or
bbb
For regex to match a url, I'd suggest the following:
\w+://[\w\._~:/?#\[\]#!$&'()*+,;=%]*
This is based on the allowed character set for a url.
For the file, what's your definition of a filename?
If you want to search for strings, that match "(at least) one to many non-fullstop characters, followed by a fullstop, followed by (at least) one to many non-fullstop characters", I'd suggest the following regex:
[^\.]+\.[^\.]+
And altogether:
(\w+://[\w\._~:/?#\[\]#!$&'()*+,;=%]*|[^\.]+\.[^\.]+)
Here's an example of working (in javascript): jsfiddle
You can test it out regex online here: http://gskinner.com/RegExr/
If it is for the purpose of flow control you can do the following:
var test = "http://ajax.googleapis.com/html5shiv.js";
// to recognize http & https
var regex = /^https?:\/\/.*/i;
var result = regex.exec(test);
if (result == null){
// no URL found code
} else {
// URL found code
}
For the purpose of capturing the file name you could use:
var test = "http://ajax.googleapis.com/html5shiv.js";
var regex = /(\w+\.\w+)$/i;
var filename = regex.exec(test);
Yes, you can use the alternation operator |. Be careful, though, because its priority is very low. Lower than sequencing. You will need to write things like /(cat)|(dog)/.
It's very hard to understand what you exactly want with so few use/test cases, but
(http://[a-zA-Z0-9\./]+)|([a-zA-Z0-9\.]+)
should give you a starting point.
If it's a URL, strip it down to the last part and treat it the same way as "just a filename".
function isFile(fileOrUrl) {
// This will return everything after the last '/'; if there's
// no forward slash in the string, the unmodified string is used
var filename = fileOrUrl.split('/').pop();
return (/.+\..+/).test(filename);
}
Try this:
var ajx = 'http://ajax.googleapis.com/html5shiv.js';
function isURL(str){
return /((\/\w+)|(^\w+))\.\w{2,}$/.test(str);
}
console.log(isURL(ajx));
Have a look at this (requires no regex at all):
var filename = string.indexOf('/') == -1
? string
: string.split('/').slice(-1)[0];
Here is the program!
<script>
var url="Home/this/example/file.js";
var condition=0;
var result="";
for(var i=url.length; i>0 && condition<2 ;i--)
{
if(url[i]!="/" && url[i]!="."){result= (condition==1)? (url[i]+result):(result);}
else{condition++;}
}
document.write(result);
</script>

Forward slash in a JavaScript variable

I have the code below.
{
var custname= "#1";
var file = "c:/temp/"+ custname + ".txt";
var fso = new ActiveXObject("Scripting.FileSystemObject");
var fh = fso.CreateTextFile(file, true, false);
fh.Write(text);
fh.Close();
}
The #1 is coming from a database and it's a customer's name. The above code works until I came across a customer name with a forward slash in it, e.g. "Company A/S".
How do I make this work for customers with the forward slash?
Replace any slashes in the customer name with another character (e.g. an underscore).
var custname= "#1";
custname = custname.replace(/\//g, '_');
...
Note the use of the g modifier on the regular expression to ensure that every slash character is replaced.
This is also why a regexp is used instead of just '/' - the substring version of String.replace won't handle repeated occurences.
You can replace (or delete) any characters not allowed by the filesystem. For example:
custname = custname.replace(/[/|&$]/g, '');
You're creating the file from the customers name as well, so when they have a '/' in their name, the file directory could look something like:
var custname= "/isuck";
var file = "c:/temp/"+ custname + ".txt";
File would equal:
c:/temp//isuck.txt
Which wouldn't be a valid file. The SMART move would be to not allow any '/' marks in a customer name, which really doesn't make sense away. Or if they HAVE to put it in that way, remove the '/' before storing it, or replace it with another character.
Store an id, eg a number, for each customer in the database and get the database to return this. Use the number for the filename. If you then need the name do another query.
If it's Windows you can't have a file name with "/" in it so personally I'd just replace all "/" with something else.
var file = "c:/temp/"+ custname.replace(/\//g, "-") + ".txt";

How to use href.replace in extjs

how to use href.replace in extjs
This is my sample:
'iconCls': 'icon_' + href.replace(/[^.]+\./, '')
href= http://localhost:1649/SFM/Default.aspx#/SFM/config/release_history.png
Now i want to get text "release_history.png", How i get it.
Thanks
If you just want the filename, it's probably easier to do:
var href = "http://localhost:1649/SFM/Default.aspx#/SFM/config/release_history.png";
var iconCls = 'icon_' + href.split('/').pop();
Update
To get the filename without the extension, you can do something similar:
var filename = "release_history.png";
var without_ext = filename.split('.');
// Get rid of the extension
without_ext.pop()
// Join the filename back together, in case
// there were any other periods in the filename
// and to get a string
without_ext = without_ext.join('.')
some regex solutions (regex including / delimiter)
as in your example code match the start of the url that can be dropped
href.replace(/^.*\//, '')
or use a regex to get the last part of the url that you want to keep
/(?<=\/)[^.\/]+\.[^.]+$/
update
or get the icon name without .png (this is using lookbehind and lookahead feature of regex)
(?<=\/)[^.\/]+(?=\.png)
Not all flavors of regex support all lookaround reatures and I think Javascript only supports lookahead. so probably your solution is this:
[^.\/]+(?=\.png)
code examples here:
http://www.myregextester.com/?r=6acb5d23
http://www.myregextester.com/?r=b0a88a0a

Categories

Resources