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)
Related
I have a string and I want to remove this data like this \(f(x) = (a+b)\)
so i am thinking to get all subsstring and then make some operation on array. But it is giving me only one stripedHtml. So not able to get how to clean it. Just wants to remove this equations.
Result will be : Here’s the evidence
const filter_data = `<p>\(f(x) = (a+b)\)</p><p>\(f(x) = (a+db)\)</p><p>\(f(x) = (a+d+c+b)\)</p>
<p>Here’s the evidence.</p>`
var strippedHtml = filter_data.substring(
filter_data.lastIndexOf("\(") + 1,
filter_data.lastIndexOf("\)")
);
console.log(strippedHtml)
JS has a replace method for this that accepts RegExp:
const filter_data = `<p>\(f(x) = (a+b)\)</p><p>\(f(x) = (a+db)\)</p><p>\(f(x) = (a+d+c+b)\)</p>
<p>Here’s the evidence.</p>`;
var strippedHtml = filter_data.replace(/\<.*?\(.*?>/g, "");
console.log(strippedHtml);
The RegExp searches for an < followed by a ( and then an > and replaces all appearances with an empty value.
In your string it will match two times and do a replace.
Maybe you have to modify the RegExp to fit your real string as it would also match text nodes containing ( but that's what I would do at this point with the given data.
You can use following regular expressions to obtain solution for only similar type of data you were provided
const filterData1 = `<p>\(f(x) = (a+b)\)</p><p>\(f(x) = (a+db)\)</p><p>\(f(x) = (a+d+c+b)\)</p><p>Here’s the evidence.</p>`
const filterData2 = `<p>\(f(x) = (a+b)\)</p><p>\(f(x) = (a+db)\)</p><p>\(f(x) = (a+d+c+b)\)</p><p>Here’s the evidence.</p><p>\(f(x) = (a+b)\)</p>`
const regEx1 = /<[^>]*>/g //regular expression to remove all html tags
const regEx2 = /\([^\)]*\)/g //regular expression to remove everything between \( and \)
const regEx3 = /[=)]/g //regular expression to remove = and )
const result1 = filterData1.replace(regEx1,'').replace(regEx2,'').replace(regEx3,'').trim()
const result2 = filterData2.replace(regEx1,'').replace(regEx2,'').replace(regEx3,'').trim()
console.log("Result1 : ",result1);
console.log("Result2 : ",result2);
I want to extract the id 1406570408 from the below url. I was wondering if there is a better way than my current try ?
let str = 'https://www.google.de/webapp/viewer/1406570408?page=1&pageType=DE-P-Global_Startpage&lat=52.5517268&lng=13.4123013';
str = str.split('/')
str = str[5].split('?')
console.log(str[0]) // 1406570408
how about using url class ?
let url = new URL("https://www.google.de/webapp/viewer/1406570408?page=1&pageType=DE-P-Global_Startpage&lat=52.5517268&lng=13.4123013")
url.pathname.split('/')[3] //equals the id
here
url.pathname contains webapp/viewer/1406570408
or use
url.pathname.split('/').pop() to remove the last element as #O.Jones pointed out
const url = "https://www.google.de/webapp/viewer/1406570408?pag…-P-Global_Startpage&lat=52.5517268&lng=13.4123013"
const url2 = "https://www.google.de/webapp/viewer/1406570408"
const url3 = "https://www.google.de/webapp/something/1406570408"
const getId = (url) => {
const match = /(?<=viewer\/)\d*/.exec(url)
return match ? match[0] : null;
}
console.log(getId(url))
console.log(getId(url2))
console.log(getId(url3))
let url = 'https://www.google.de/webapp/viewer/1406570408?page=1&pageType=DE-P-Global_Startpage&lat=52.5517268&lng=13.4123013';
const segments = new URL(url).pathname.split('/');
const last = segments.pop() || segments.pop();
console.log(last);
Here is the single line plain javascript methods of Arrays
let str = 'https://www.google.de/webapp/viewer/1406570408?page=1&pageType=DE-P-Global_Startpage&lat=52.5517268&lng=13.4123013';
str = str.split('?')[0].split('/').reverse()[0]
console.log(str) // 1406570408
let str = 'https://www.google.de/webapp/viewer/1406570408?page=1&pageType=DE-P-Global_Startpage&lat=52.5517268&lng=13.4123013';
console.log(str.match(/\d+/)[0]);
Use an regrex to find an numeric value inside a url string
Best way is to parse the URL with the URL JavaScript API, and then extract the piece of data you need from the pathname property provided to you by the URL.
An example for your usecase:
let str = 'https://www.google.de/webapp/viewer/1406570408?page=1&pageType=DE-P-Global_Startpage&lat=52.5517268&lng=13.4123013';
let url = new URL(str); // create an instance of the URL API
let pathname = url.pathname; // pathname property
let segments = pathname.split('/'); // split pathname by / slash
let last_item = segments.slice(-1)[0] || null; // grab the last item from pathname array
console.log(last_item);
Your output will be: 1406570408.
If your pathname is '/' or no pathname at all, you'll receive a null which you can handle later.
Also, the above code could be shortened into:
let str = 'https://www.google.de/webapp/viewer/1406570408?page=1&pageType=DE-P-Global_Startpage&lat=52.5517268&lng=13.4123013';
let last_item = (new URL(str)).pathname.split('/').slice(-1)[0] || null;
console.log(last_item);
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"
I have a URL
https://www.yellowpages.com/search?search_terms=Generator+Repair&geo_location_terms=Adamsville%2C+Alabama
I want to get search_terms (Generator+Repair) and geo_location_terms (Adamsville%2C+Alabama)
How I can do this?
The easiest and most idiomatic way to do this in JavaScript is using the URL class:
const url = new URL('https://www.yellowpages.com/search?search_terms=Generator+Repair&geo_location_terms=Adamsville%2C+Alabama')
console.log(url.searchParams.get('search_terms'));
console.log(url.searchParams.get('geo_location_terms'));
MDN reference here.
You can use the following Javascript code to store the GET parameters into an object:
<script>
var URL = "https://www.yellowpages.com/search?search_terms=Generator+Repair&geo_location_terms=Adamsville%2C+Alabama";
var result = {};
URL.substring(URL.indexOf("?") + 1).split('&').forEach(function(x){
var arr = x.split('=');
arr[1] && (result[arr[0]] = arr[1]);
});
console.log(result.search_terms);
//OUTPUT: "Generator+Repair"
console.log(result.geo_location_terms);
//OUTPUT: "Adamsville%2C+Alabama"
</script>
You can use the following regex to get the 2 values:
/search_terms=(.*)&geo_location_terms=(.*)/
This is a very basic regex, that starts by matching 'search_terms=' then creates a Group that matches any number of any char up to the '&' sign, then matches 'geo_location_terms=' and finally creates a Group that matches any number of any char.
Your desired output will be in Group 1 and Group 2.
How to use:
var url = 'https://www.yellowpages.com/search?search_terms=Generator+Repair&geo_location_terms=Adamsville%2C+Alabama';
var regex = /search_terms=(.*)&geo_location_terms=(.*)/;
var match = url.match(regex);
var search_terms = match[1];
var geo_location_terms = match[2];
A quick simple regex question
I have a domain name in a string that I need to strip - There is always http://www. and the domain always ends in "/"
g_adv_fullpath_old = g_adv_fullpath_old.replace(/http\:\/\/www\.(.*?)\//ig, '');
how do I create the regex to strip the domain name?
Any help would be appreciated
I would simply split on "/". For example:
>>> "http://www.asdf.com/a/b/c".split("/").slice(3).join("/")
'a/b/c'
Why complications? Simple indexOf will do.
First remove http://www (10 characters), then everything before the first slash.
var s = "http://www.google.com/test";
s = s.substr(10);
s = s.substr(s.indexOf('/'));
alert(s);
Or split, as David suggests.
An example
If you are looking to remove the http://www. and the following slash (plus anything after it) Try:
g_adv_fullpath_old.replace(/http:\/\/www\.(.*?)\/.*/ig, '$1')
You can also extend the stringobject so it supports urlParts
Example
http://jsfiddle.net/stofke/Uwdha/
Javascript
String.prototype.urlParts = function() {
var loc = this;
loc = loc.split(/([a-z0-9_\-]{1,5}:\/\/)?(([a-z0-9_\-]{1,}):([a-z0-9_\-]{1,})\#)?((www\.)|([a-z0-9_\-]{1,}\.)+)?([a-z0-9_\-]{3,})((\.[a-z]{2,4})(:(\d{1,5}))?)(\/([a-z0-9_\-]{1,}\/)+)?([a-z0-9_\-]{1,})?(\.[a-z]{2,})?(\?)?(((\&)?[a-z0-9_\-]{1,}(\=[a-z0-9_\-]{1,})?)+)?/g);
loc.href = this;
loc.protocol = loc[1];
loc.user = loc[3];
loc.password = loc[4];
loc.subdomain = loc[5];
loc.domain = loc[8];
loc.domainextension = loc[10];
loc.port = loc[12];
loc.path = loc[13];
loc.file = loc[15];
loc.filetype = loc[16];
loc.query = loc[18];
loc.anchor = loc[22];
//return the final object
return loc;
};
Usage:
var link = "http://myusername:mypassword#test.asdf.com/a/b/c/index.php?test1=5&test2=789#tite";
var path = link.urlParts().path;
var path = link.urlParts().user;