Slice URL to get the file name in Vue - javascript

I have a file url and I need to slice it for showing the file to the users. I have successfully sliced it using substring but what if the string to slice isn't fixed. Like this /media/users/3/sample.docx. I wanted to show sample.docx only so I used substring but what if the numbers before that, increases like the number 3? How can do it the better way?
sliceString(value) {
return value.substring(15)
}
{{sliceString(data.file)}}

Take the last index of /, add 1 to it and use in the substring method :
sliceString(value) {
let lastSlashIndex=value.lastIndexOf('/')
return value.substring(lastSlashIndex+1)
}
Example:
let url = 'sample.com/media/users/3/sample.docx'
let lastIndex= url.lastIndexOf('/');
console.log(url.substring(lastIndex+1))

Try to use value.lastIndexOf()
sliceString(value) {
return value.substring(value.lastIndexOf("/")+1)
}
{{sliceString(data.file)}}

Try using split:
const url = 'sample.com/media/users/3/sample.docx';
url = url.split('/');
len = url.length;
const sample = url[len-1];
console.log(sample) // 'sample.docx'

You can use regex to do it like that
const url = 'sample.com/media/users/3/sample.docx'
console.log(url.match(/[^\/]+$/)[0])

This should shrink the URL to just the filename even if there are query string parameters :
const fileString = 'file:///folder1/folder2/folder3/filename.extension?possibleQueries';
sliceURL = ((url) => {
lastChar = url.length;
if (url.lastIndexOf('?') > -1) {
lastChar = url.lastIndexOf('?');
};
return (url.substring(url.lastIndexOf("/") + 1, lastChar));
})
(fileString); // Expected output: "filename.extension"

Related

How to find text between 2 characters with multiple occurrences?

Given the below string, what would be the most efficient way to get the file ID? The portion wanted: XXXXXXXXXXXxxxxxxxxXXX, which is between / and /view
The attempt below works, but is it really needed to reverse the string twice?
let = url = 'https://drive.google.com/file/d/1pnEX1OXXXXXXu6z9dPV5ZZ5VHqPU--6/view?usp=share_link'
url = reverseString(url)
let id = url.split('weiv/').pop().split('/')[0]
id = reverseString(id)
console.log('URL:' + id)
function reverseString(str) {
var splitString = str.split("");
var reverseArray = splitString.reverse();
var joinArray = reverseArray.join("");
return joinArray;
}
This solution searches for the "/d/" portion and advances three characters to begin a string.slice, continuing until the next occurence of /. Provided /d/ is always before the id portion, this should be reliable.
const url = 'https://drive.google.com/file/d/1pnEX1OXXXXXXu6z9dPV5ZZ5VHqPU--6/view?usp=share_link';
const id = url.slice(url.indexOf("/d/")+3, url.indexOf("/",url.indexOf("/d/")+3 ));
console.log(id);
I'd solve this with a simple regex.
const url = 'https://drive.google.com/file/d/1pnEX1OXXXXXXu6z9dPV5ZZ5VHqPU--6/view?usp=share_link';
const m = url.match(/^.*?\/.\/(.*?)\/view.*$/);
console.log(m[1])
you can use substring to get the value between /d/ and /view
let = url = 'https://drive.google.com/file/d/1pnEX1OXXXXXXu6z9dPV5ZZ5VHqPU--6/view?usp=share_link'
const fileId = url.substring(url.lastIndexOf("/d/") + 3, url.lastIndexOf("/view"));
console.log(fileId)

Extract domain from a string using Javascript?

I have an string which include many website url but i want to extract the only url that is out side these bracket [ ].
Can someone correct this ?
Note : Output Must be www.google.com and it not necessary that domain name outside [ ] will come at the end of string.
var str = '[[www.abc.com/corporate/partner/just-a-test]]acdascvdvsa.1563e24e32e42|[[www.abc.com/corporate/partner/just-a-test]]1563e24e32e42.1563e24e32e42|[[www.abc.com/instruments/infrared-guided-measurement/]]www.google.com&1566805689640.1566806059701.3';
// String can include https and instead of .com there can be .in
var arr = str.split("|");
function domainName(str) {
var match = str.match(/^(?:https?:\/\/)?(?:w{3}\.)?([a-z\d\.-]+)\.(?:[a-z\.]{2,10})(?:[\w\.-]*)*/);
if (match != null && match.length > 0) {
return match;
} else {
return null;
}
}
var domainname = domainName(str);
var domain = domainname;
console.log(domain);
Replace all occurrences of [[, followed by non-brackets, followed by ]] with a space::
var str = '[[www.abc.com/corporate/partner/just-a-test]]acdascvdvsa.1563e24e32e42|[[www.abc.com/corporate/partner/just-a-test]]1563e24e32e42.1563e24e32e42|[[www.abc.com/instruments/infrared-guided-measurement/]]www.google.com&1566805689640.1566806059701.3';
const result = str.replace(/\[\[[^[\]]*\]\]/g, ' ');
console.log(result);
Then you can search for URLs in the replaced string.
As CertainPerformance Suggest you can exclude the url that is in [ ] using replace then by using regex you can extract the domain name. Below is the code :
var str = '[[www.abc.com/corporate/partner/just-a-test]]acdascvdvsa.1563e24e32e42|[[www.abc.com/corporate/partner/just-a-test]]1563e24e32e42.1563e24e32e42|[[www.abc.com/instruments/infrared-guided-measurement/]]www.google.com&1566805689640.1566806059701.3';
var str = str.replace(/\[\[[^[\]]*\]\]/g, '');
var ptrn = /^(?:https?:\/\/)?(?:w{3}\.)?([a-z\d\.-]+)\.(?:[a-z\.]{2,10})(?:[\w\.-]*)*/g;
var i, value, domain, len, array;
array = str.split("|");
len = array.length;
for(i=0; len > i; i++) {
value = array[i].match(ptrn);
if (value !== null) {
domain = value;
}
else {
domain = "Not Found";
}
}
document.write("Domain is = ", domain);
Two main steps:
Create a regular expression that matches your desired pattern.
Use String.match()
Example:
// match all URLs
// let regex = /((([A-Za-z]{3,9}:(?:\/\/)?)(?:[\-;:&=\+\$,\w]+#)?[A-Za-z0-9\.\-]+|(?:www\.|[\-;:&=\+\$,\w]+#)[A-Za-z0-9\.\-]+)((?:\/[\+~%\/\.\w\-_]*)?\??(?:[\-\+=&;%#\.\w_]*)#?(?:[\.\!\/\\\w]*))?)/g;
// match only the URL outside of the brackets
let regex = /(((([A-Za-z]{3,9}:(?:\/\/)?)(?:[\-;:&=\+\$,\w]+#)?[A-Za-z0-9\.\-]+|(?:www\.|[\-;:&=\+\$,\w]+#)[A-Za-z0-9\.\-]+)((?:\/[\+~%\/\.\w\-_]*)?\??(?:[\-\+=&;%#\.\w_]*)#?(?:[\.\!\/\\\w]*))?))(([^[\]]+)(?:$|\[))/g;
function getUrlsFromText(input) {
return input.match(regex);
}
console.log(getUrlsFromText('[[www.abc.com/corporate/partner/just-a-test]]acdascvdvsa.1563e24e32e42|[[www.abc.com/corporate/partner/just-a-test]]1563e24e32e42.1563e24e32e42|[[www.abc.com/instruments/infrared-guided-measurement/]]www.google.com&1566805689640.1566806059701.3'));
Note that I borrowed the URL matching part of the regular expression from here. If you don't want the query string to be included (as it is on the google.com match), you can modify the regex as desired.
this can be achieve by split
var str = '[[www.abc.com/corporate/partner/just-a-test]]acdascvdvsa.1563e24e32e42|[[www.abc.com/corporate/partner/just-a-test]]1563e24e32e42.1563e24e32e42|[[www.abc.com/instruments/infrared-guided-measurement/]]www.google.com&1566805689640.1566806059701.3';
let ans=str.split("]")[6]
let finalAns=ans.split("&")[0]
console.log(finalAns)
var dirtySource = "https://example.com/subdirectory";
var dirtyPos = dirtySource.indexOf("://"); // works for http and https
var cleanSource = dirtySource.substr(dirtyPos+3);
cleanSource = cleanSource.split("/")[0]; // trim off subdirectories

Remove sections of url to only keep file name

I want to remove everything in the URL and only keep the name of the file/image. The URL is a dynamic input/variable.
Code:
var str = "http://website.com/sudir/sudir/subdir/Image_01.jpg";
str = str.replace("http://website.com/sudir/sudir/subdir/", "")
.replace(/[^a-z\s]/gi, ' ').replace("_", " ")
.replace("subdir", "").toLowerCase().slice(0,-4);
You can do this easily with lastIndexOf():
var str = "http://website.com/sudir/sudir/subdir/Image_01.jpg";
str.substring(str.lastIndexOf("/") + 1)
//"Image_01.jpg"
This function will give you the file name,
function GetFilename(url)
{
if (url)
{
var m = url.toString().match(/.*\/(.+?)\./);
if (m && m.length > 1)
{
return m[1];
}
}
return "";
}
From How to catch the end filename only from a path with javascript?
var filename = path.replace(/.*\//, '');
From Getting just the filename from a path with Javascript
var fileNameIndex = yourstring.lastIndexOf("/") + 1;
var filename = yourstring.substr(fileNameIndex);
I know you haven't specified the exact URL format and whether this may be possible in your situation, but this may be a solution worth considering.
Javascript
var str = "http://website.com/sudir/sudir/subdir/Image_01.jpg?x=y#abc";
console.log(str.split(/[?#]/)[0].split("/").slice(-1)[0]);
str = "http://website.com/sudir/sudir/subdir/Image_01.jpg";
console.log(str.split(/[?#]/)[0].split("/").slice(-1)[0]);
On jsfiddle
You can always Regex to extract data from strings:
The Regex to extract data from URL:
"http://website.com/sudir/sudir/subdir/(?<FileName>[0-9A-Za-z._]+)"

How to get the last two characters of url with jQuery?

I have a url with the following format:
base/list.html?12
and I want to create a variable which will be equal to the digits after the question mark in the url of the page. Something like:
var xxx = anything after the ? ;
Then I need to load dynamic data into that page using this function:
if(document.URL.indexOf(xxx) >= 0){
alert('Data loaded!');
}
How can I achieve this? and are the codes above correct?
Thanks
You can use split to get the characters after ? in the url
var xxx = 'base/list.html?12';
var res = xxx.split('?')[1];
or for current page url
var res = document.location.href.split('?')[1];
res = document.location.href.split('?')[1];
Duplicate of 6644654.
function parseUrl( url ) {
var a = document.createElement('a');
a.href = url;
return a;
}
var search = parseUrl('base/list.html?12').search;
var searchText = search.substr( 1 ); // removes the leading '?'
document.location.search.substr(1) would also work

Javascript to extract *.com

I am looking for a javascript function/regex to extract *.com from a URI... (to be done on client side)
It should work for the following cases:
siphone.com = siphone.com
qwr.siphone.com = siphone.com
www.qwr.siphone.com = siphone.com
qw.rock.siphone.com = siphone.com
<http://www.qwr.siphone.com> = siphone.com
Much appreciated!
Edit: Sorry, I missed a case:
http://www.qwr.siphone.com/default.htm = siphone.com
I guess this regex should work for a few cases:
/[\w]+\.(com|ca|org|net)/
I'm not good with JavaScript, but there should be a library for splitting URIs out there, right?
According to that link, here's a "strict" regex:
/^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:#]*)(?::([^:#]*))?)?#)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/
As you can see, you're better off just using the "library". :)
This should do it. I added a few cases for some nonmatches.
var cases = [
"siphone.com",
"qwr.siphone.com",
"www.qwr.siphone.com",
"qw.rock.siphone.com",
"<http://www.qwr.siphone.com>",
"hamstar.corm",
"cheese.net",
"bro.at.me.come",
"http://www.qwr.siphone.com/default.htm"];
var grabCom = function(str) {
var result = str.match("(\\w+\\.com)\\W?|$");
if(result !== null)
return result[1];
return null;
};
for(var i = 0; i < cases.length; i++) {
console.log(grabCom(cases[i]));
}
var myStrings = [
'siphone.com',
'qwr.siphone.com',
'www.qwr.siphone.com',
'qw.rock.siphone.com',
'<http://www.qwr.siphone.com>'
];
for (var i = 0; i < myStrings.length; i++) {
document.write( myStrings[i] + '=' + myStrings[i].match(/[\w]+\.(com)/gi) + '<br><br>');
}
I've placed given demo strings to the myStrings array.
i - is index to iterate through this array. The following line does the matching trick:
myStrings[i].match(/[\w]+\.(com)/gi)
and returns the value of siphone.com. If you'd like to match .net and etc. - add (com|net|other) instead of just (com).
Also you may find the following link useful: Regular expressions Cheat Sheet
update: missed case works too %)
You could split the string then search for the .com string like so
var url = 'music.google.com'
var parts = url.split('.');
for(part in parts) {
if(part == 'com') {
return true;
}
{
uri = "foo.bar.baz.com"
uri.split(".").slice(-2).join(".") // returns baz.com
This assumes that you want just the hostname and tld. It also assumes that there is no path information either.
Updated now that you also need to handle uris with paths you could do:
uri.split(".").slice(-2).join(".").split("/")[0]
Use regexp to do that. This way modifications to the detections are quite easy.
var url = 'www.siphone.com';
var domain = url.match(/[^.]\.com/i)[0];
If you use url.match(/(([^.]+)\.com)[^a-z]/i)[1] instead. You can assure that the ".com" is not followed by any other characters.

Categories

Resources