Extract id from url string - javascript

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);

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)

How can remove page and pageSize from given text?

"?page=2&pageSize=12&query=hex"
I have the above text I want to remove page and pageSize along with value. After removing the page and pageSize my text should look like given below.
"?query=hex"
You can use URLSearchParams to remove params of the query:
const queryString = "?page=2&pageSize=12&query=hex";
const searchParams = new URLSearchParams(queryString);
searchParams.delete("page");
searchParams.delete("pageSize");
const resultQuery = `?${searchParams.toString()}`;
Reference:
https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams
here is my solution
text.replace(/(page=\d+&?)|(pageSize=\d+&?)/g, '')
Here's one way of doing it without any third-party library:
const input = "?page=2&pageSize=12&query=hex"
const parts = input
.replace(/^\?/, "")
.split("&")
.filter(p => !/^(page|pageSize)/.test(p))
const output = "?" + parts.join("&")
console.log(output)
Using regex you can do that as below:
const str = "?page=2&pageSize=12&query=hex";
console.log(str.replace(/page.*&/g, ""));
Here, maybe this will help. Simple to implement and understand.
var str = "?page=2&pageSize=12&query=hex";
var finalStr = '?' + str.substring(str.indexOf('query='))
console.log(finalStr)

Slice URL to get the file name in Vue

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"

Replace the some special symbol from query string in javascript

I want to get these type of params PropertyType[] in my url instead of PropertyType[0].How to replace it?
Actual URL
City=Antwerp,Archbold,Berkey&PropertyType[0]=Residential&minbed=1&minbath=1&min_price=10000&max_price=2500000
I want these type of url
City=Antwerp,Archbold,Berkey&PropertyType[]=Residential&minbed=1&minbath=1&min_price=10000&max_price=2500000
var serializeData = $('#searchstring').val();
console.log(serializeData);
var data = JSON.stringify(serializeData);
var url1 = data.replace(/['"]/g,'');
var url = url1.replace(/\+/g,' ');
var uri_dec = decodeURIComponent(url);
You can use \d regular expression to replace all digits that appear in []
var url = 'City=Antwerp,Archbold,Berkey&PropertyType[0]=Residential&minbed=1&minbath=1&min_price=10000&max_price=2500000';
var regEx = new RegExp(/\[\d+\]/,'gim');
var newURL = url.replace(regEx, (match) => '[]');
console.log(newURL)
you can replace these using regex in js
url = ""your_url"
new_url = url.replace(/([\d])/g, '')

Single regexp to get page URL but exclude port number from a full URL

I'm trying to come up with a regexp to get the page URL from the full URL but exclude a possible port number from it. So far I came up with the following JS:
var res = url.match(/^.*\:\/\/(?:www2?.)?([^?#]+)/i);
if(res)
{
var pageURL = res[1];
console.log(pageURL);
}
If I call it for this:
var url = "http://www.example.com/php/page.php?what=sw#print";
I get the correct answer: example.com/php/page.php
But if I do:
var url = "http://www.example.com:80/php/page.php?what=sw#print";
I need it to return example.com/php/page.php instead of example.com:80/php/page.php.
I can remove it with the second regexp, but I was curious if I could do it with just one (for speed)?
You can modify your regex to this:
/^.*\:\/\/(?:www2?.)?([^/:]+)(?:[^:]*:\d+)?([^?#]+)/i
RegEx Demo
It will return 2 matches:
1: example.com
2: /php/page.php
as match[1] and match[2] respectively for both inputs that you can concatenate.
http://www.example.com/php/page.php?what=sw#print
OR
http://www.example.com:80/php/page.php?what=sw#print
Update: Here are performance results on jsperf.com that shows regex method is fastest is of all.
Keep it simple:
~ node
> "http://www.example.com:3000/php/page.php?what=sw#print".replace(/:\d+/, '');
'http://www.example.com/php/page.php?what=sw#print'
> "http://www.example.com/php/page.php?what=sw#print".replace(/:\d+/, '');
'http://www.example.com/php/page.php?what=sw#print'
Why would you use a regex at all?
EDIT:
As pointed out by #c00000fd: Because document might not be available and document.createElement is very slow compared to RegExp - see:
http://jsperf.com/url-parsing/5
http://jsperf.com/hostname-from-url
Nevertheless I will leave my original answer for reference.
ORIGINAL ANSWER:
Instead you could just use the Anchor element:
Fiddle:
http://jsfiddle.net/12qjqx7n/
JS:
var url = 'http://foo:bar#www.example.com:8080/php/page.php?what=sw#print'
var a = document.createElement('a');
a.href = url;
console.log(a.hash);
console.log(a.host);
console.log(a.hostname);
console.log(a.origin);
console.log(a.password);
console.log(a.pathname);
console.log(a.port);
console.log(a.protocol);
console.log(a.search);
console.log(a.username);
Additional information:
http://www.w3schools.com/jsref/dom_obj_anchor.asp
How about a group for matching the port, if present?
var url = "http://www.example.com:80/php/page.php?what=sw#print";
var res = url.match(/^.*\:\/\/(?:www2?.)?([^?#\/:]+)(\:\d+)?(\/[^?#]+)/i);
if(res)
{
var pageURL = res[1]+res[3];
console.log(res, pageURL);
}
Try
var url = "http://www.example.com:80/php/page.php?what=sw#print";
var res = url.split(/\w+:\/\/+\w+\.|:+\d+|\?.*/).join("");
var url = "http://www.example.com:80/php/page.php?what=sw#print";
var res = url.split(/\w+:\/\/+\w+\.|:+\d+|\?.*/).join("");
document.body.innerText = res;
You could use replace method to modify your original string or Url,
> var url = "http://www.example.com/php/page.php?what=sw#print";
undefined
> var url1 = "http://www.example.com:80/php/page.php?what=sw#print";
undefined
> url.replace(/^.*?:\/\/(?:www2?.)?([^/:]+)(?::\d+)?([^?#]+).*$/g, "$1$2")
'example.com/php/page.php'
> url1.replace(/^.*?:\/\/(?:www2?.)?([^/:]+)(?::\d+)?([^?#]+).*$/g, "$1$2")
'example.com/php/page.php'
DEMO

Categories

Resources