Get a portion of string path - javascript

I have a file path as shown below.The last part (i.e. video2.mp4) is dynamically changed.I'm using Javascript/Typescript.
file:///data/user/0/com.sleep.app/files/sleep-videos/video2.mp4
Question: How to get the file:///data/user/0/com.sleep.app/files/sleep-videos/ part only from above string.

var string = 'file:///data/user/0/com.sleep.app/files/sleep-videos/video2.mp4';
var stringPart = string.substring(0,string.lastIndexOf("/")+1);

If only the filename changes try something like here
^(.+)/([^/]+)$
Try it at regexr. Your first group is the dirname, the second group the basename.
If you have further requirements/information (e.g. which tools you use), please refine your question.

var url = "file:///data/user/0/com.sleep.app/files/sleep-videos/video2.mp4";
url= url.split("/");
url.pop();
url = url.join("/");

Related

Get file name from url with javascript

I am having a little problem. I want to get the file name
(横 浜 プ レ _ 図 面 デ ー タ .pdf)
from the url below. I don't know how to use regex to find the file name.
Hope everybody help please.
https://reclaim-files-dev.s3.ap-northeast-1.amazonaws.com/attachment/横浜プレ_図面データ.pdf?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIASUJZK2B4ZLI77WWZ%2F20200303%2Fap-northeast-1%2Fs3%2Faws4_request&X-Amz-Date=20200303T042736Z&X-Amz-Expires=300&X-Amz-Signature=b8b00cb04dbe5a73de8230327651636784a0c9d7979a5666e13b54d67f116703&X-Amz-SignedHeaders=host
Create an URL and let it parse:
const url = new URL(yourUrlString);
Filter the file name:
const fileName = url.pathname.replace(/^.*[\\\/]/, "");
If the filename always follows /attachment/ in the URL, and presumably is always followed with the ? and the rest of the parameters:
Assuming the entire url is assigned to urlString
let startIndex = urlString.indexOf("/attachment/");
let endIndex = urlString.indexOf("?");
let fileName = urlString.substring(startIndex, fileName);
This will find any filename regardless of file type (you mention pdf, but this would find files with other extensions).
var url = 'https://reclaim-files-dev.s3.ap-northeast-1.amazonaws.com/attachment/横浜プレ_図面データ.pdf?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIASUJZK2B4ZLI77WWZ%2F20200303%2Fap-northeast-1%2Fs3%2Faws4_request&X-Amz-Date=20200303T042736Z&X-Amz-Expires=300&X-Amz-Signature=b8b00cb04dbe5a73de8230327651636784a0c9d7979a5666e13b54d67f116703&X-Amz-SignedHeaders=host';
var url2 = url.substring(0, url.indexOf('?X'));
console.log(url2.substring(url2.lastIndexOf('/') + 1));
I guess you can do this without regex
x = "https://reclaim-files-dev.s3.ap-northeast-1.amazonaws.com/attachment/横浜プレ_図面データ.pdf?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIASUJZK2B4ZLI77WWZ%2F20200303%2Fap-northeast-1%2Fs3%2Faws4_request&X-Amz-Date=20200303T042736Z&X-Amz-Expires=300&X-Amz-Signature=b8b00cb04dbe5a73de8230327651636784a0c9d7979a5666e13b54d67f116703&X-Amz-SignedHeaders=host"
y = x.split('/')
["https:", "", "reclaim-files-dev.s3.ap-northeast-1.amazonaws.com", "attachment", "横浜プレ_図面データ.pdf?X-Amz-Algorithm=AWS4-HMAC-SHA256&…979a5666e13b54d67f116703&X-Amz-SignedHeaders=host"]
your attachment will be in the 4th index
str = y[4].substr(0, y[4].indexOf('.pdf'))
If you are looking to get the file name from specifically this arrangement of a URL, then simply split by the first argument (?) and then split by forward slash. This will give you an array which you can reverse. The first element of this array will be your file name:
function get_file(url_string){
return url_string.split('?')[0].split('/').reverse()[0];
}
If you want to go a step further, you can then split the result by (.) in order to get the actual name and the file extension in a single step:
function get_file(url_string){
return url_string.split('?')[0].split('/').reverse()[0].split('.');
}
Note: as previously mentioned, this only works with your URL arrangement.

how change url array params by jquery or javascript

I need to change URL param By JavaScript or jquery.
My URL is:
domain.com/path/to/reach/5?order%5Bsort%5D=2&c=5
I want change paramt c and order[sort]
like this:
domain.com/?order%5Bsort%5D=3&c=15
domain.com/5?order%5Bsort%5D=2&c=16
domain.com/5?order%5Bsort%5D=1&c=17
my code is this:
regEx = /([?&]p)=([^#&]*)/g;
dataUrl = dataUrl.replace(regEx, '$1='+page);
regEx = /([?&]order[[]column[]])=([^#&]*)/g;
dataUrl = dataUrl.replace(regEx, '$1='+data["order[column]"]);
but don't work!!!!
try this:
let orderSort=4,c=6;
let url='domain.com/path/to/reach/5?order%5Bsort%5D=2&c=5';
let result=url.replace(/order%5Bsort%5D=\d*&c=\d*/,'order%5Bsort%5D='+orderSort+'&c='+c);
console.log(result);//domain.com/path/to/reach/5?order%5Bsort%5D=4&c=6
explanation:
i extract the key you offered and use the value to make a new and target string.
then, replace function works by replace the whole string the reg matches with the target string.
Because of the order of the parameters, it's not possible to use your code. So I used the following code, but the first two lines worked correctly, but the second two lines have problems and add the value to it every time.
dataUrl = dataUrl.replace(/c=\d*/, 'c='+count);
dataUrl = dataUrl.replace(/p=\d*/, 'p='+page);
dataUrl = dataUrl.replace(/order%5Bsort%5D=\d*/, 'order%5Bsort%5D='+dataObj["order[sort]"]); //
dataUrl = dataUrl.replace(/order%5Bcolumn%5D=\d*/, 'order%5Bcolumn%5D='+dataObj["order[column]"]);

How to get base url from FTP address?

For example I have a url like:
ftp://xxx:xxx#ftp.example.com/BigFile.zip
How can I get example.com from this url using javascript/jquery?
You can get the browser to parse the URL for you like this :
var a = document.createElement('a');
a.href = 'ftp://xxx:xxx#ftp.example.com/BigFile.zip';
var host = a.hostname;
That gets you the hostname, which in this case would be ftp.example.com, if for some reason you have to remove the subdomain, you can do
var domain = host.split('.');
domain.shift();
var domain = domain.join('.');
FIDDLE
Here's the different parts to a URL -> https://developer.mozilla.org/en-US/docs/Web/API/Location#wikiArticle
Here is using javascript RegExp
input = "ftp://xxx:xxx#ftp.example.com/BigFile.zip";
pattern = new RegExp(/ftp:\/\/\S+?#\S+?\.([^\/]+)/);
match = pattern.exec(input);
alert(match[1]);
You can also use i at the end of regex to make it case insensitive.
pattern = new RegExp(/ftp:\/\/\S+?#\S+?\.([^\/]+)/i);
You can use jquery like this:
var url = "ftp://xxx:xxx#ftp.example.com/BigFile.zip";
var ahref = $('<a>', { href:url } )[0]; // create an <a> element
var host = ahref.hostname.split('.').slice(1).join('.'); // example.com
You can have a regex to do this for you.
url = 'ftp://xxx:xxx#ftp.example.com/BigFile.zip'
base_address = url.match(/#.*\//)[0];
base_address = base_address.substring(1, base_address.length-1)
This would contain ftp.example.com though. You can fine tune it as per your need.
I just wanted to try/add something different (can't bet for performance or the general solution, but it works and hey ! without DOM/regexp involved):
var x="ftp://xxx:xxx#ftp.example.com/BigFile.zip"
console.log((x.split(".")[1]+ "." + x.split(".")[2]).split("/")[0]);
For the given case can be shortest since always will be ".com"
console.log(x.split(".")[1]+ ".com");
Another (messy) approach (and will work with .com.something:
console.log(x.substring((x.indexOf("#ftp"))+5,x.indexOf(x.split("/")[3])-1));
And well on this we're dependend about having "#ftp" and the slashes "/" (at least 3 of them or one after the .com.something) for example would not work with: ftp://xxx:xxx#ftp.example.com
Last update This will be my best
without DOM/RegExp, nicer (but also confusing) that the previous ones
solves the problem about having or don't the slashes,
still dependant on having "#ftp." in the string.
works with .com.something.whatever
(function (splittedString){
//this is a bit nicer, no regExp, no DOM, avoid abuse of "split"
//method over and over the same string
//check if we have a "/"
if(splittedString.indexOf("/")>=0){
//split one more time only to get what we want.
return (console.log(splittedString.split("/")[0]));
}
else{
return (console.log(splittedString));//else we have what we want
}
})(x.split("#ftp.")[1]);
As always it depends how maintainable you want your code to be, I just wanted to honor the affirmation about there's more than one way to code something. My answer for sure is not the best, but based on it you could improve your question.

Checking a specific uri in the current url - Jquery

I am trying to check if the current url
base_url/index.php?name0=value0&name1=value1&name2=value2...
contains a specific name=value. I tried this
var path = $.inArray('name=value', $(location).attr('href').split('&'));
if (path > -1){ triggers my function...}
But I guess that this wouldn't work if the url is url encoded. Is there a way to check if the url contains name=value without checking all the conditions (split('&') or split('%26')) ?
Split will always work, because & part of url is not encoded if it split parameters. However, you can have name or value encoded in the url. To search for them, you should use encodeURI like that:
var path = $.inArray(encodeURI('name=value'), $(location).attr('href').split('&'));
if (path > -1){ triggers my function...}
You can use core javascript for this:
var parameterName = 'name0';
var parameterValue = 'value0';
var path = decodeURI(location.href).indexOf(parameterName+'='+parameterValue);
if (path > -1){
triggers my function...
}
EDIT: I've tested it more and neither solution is perfect: mine fails when you have something before the specified name value, for example: varname0 when you check name0 will be found and that's not correct, yours (and monshq's) doesn't check the first value/pair which follows ? character.
How can I get query string values? is something you're looking for.

javascript or jquery - get the last 2 characters of href

I need to get the last 2 characters from the href of a link and place them into a string.
I'm sure this is fairly simple but I seem to be struggling.
Here's the link
test
I need to grab the "bb" part of the href.
Presuming link is a reference to the element:
var chars = link.href.substr(-2);
If you need to get the reference to the link, it is best to give the link an ID attribute, e.g. <a href="../mypage/?code=bb" id="myLink">, where myLink is something that describes the link's purpose. You can then do this:
var chars = document.getElementById('myLink').href.substr(-2);
Finally, if what you want is the code parameter from your link, it may be best to parse the URL into parts. If there is a chance that your URL may be more complex that what you've shown, you should do real URL parsing. As Rahul has pointed out in his answer there are some jQuery plugins that perform this function.
try
$(function() {
var res = $('a').attr('href').split(/=/)[1]
alert(res);
});
This will not grab the last two character, but everything after the = sign which works probably more generic. And even if the <center> cannot hold, regex could look like
$(function() {
var href = $('a').attr('href'),
res = /\\?code=(\w+)/.exec(href);
alert(res[1]);
});
var href = $('a').attr('href');
var last2char = href.substr(href.length-2);
You can try for some querystring plugins which might be a better option.

Categories

Resources