Trying to split following url - javascript

I'm trying to split following URL:
http://www.store.com/products.aspx/Books/The-happy-donkey
in order to get only store.
How can this be done?

To do something as generic as possible I'd do something like:
const url = new URL('http://www.store.com/products.aspx/Books/The-happy-donkey');
const { hostname } = url;
const domain = hostname.match(/^www\.(\w+)\.com/);
console.log(domain[1]);

Use below code
//window.location.href
let str = "http://www.store.com/products.aspx/Books/The-happy-donkey";
const words = str.split('.');
console.log(words[1]);

Related

How to get avatar file type [duplicate]

How do I find the file extension of a URL using javascript?
example URL:
http://www.adobe.com/products/flashplayer/include/marquee/design.swf?width=792&height=294
I just want the 'swf' of the entire URL.
I need it to find the extension if the url was also in the following format
http://www.adobe.com/products/flashplayer/include/marquee/design.swf
Obviously this URL does not have the parameters behind it.
Anybody know?
Thanks in advance
function get_url_extension( url ) {
return url.split(/[#?]/)[0].split('.').pop().trim();
}
example:
get_url_extension('https://example.com/folder/file.jpg');
get_url_extension('https://example.com/fold.er/fil.e.jpg?param.eter#hash=12.345');
outputs ------> jpg
Something like this maybe?
var fileName = 'http://localhost/assets/images/main.jpg';
var extension = fileName.split('.').pop();
console.log(extension, extension === 'jpg');
The result you see in the console is.
jpg true
if for some reason you have a url like this something.jpg?name=blah or something.jpg#blah then you could do
extension = extension.split(/\#|\?/g)[0];
drop in
var fileExtension = function( url ) {
return url.split('.').pop().split(/\#|\?/)[0];
}
For the extension you could use this function:
function ext(url) {
// Remove everything to the last slash in URL
url = url.substr(1 + url.lastIndexOf("/"));
// Break URL at ? and take first part (file name, extension)
url = url.split('?')[0];
// Sometimes URL doesn't have ? but #, so we should aslo do the same for #
url = url.split('#')[0];
// Now we have only extension
return url;
}
Or shorter:
function ext(url) {
return (url = url.substr(1 + url.lastIndexOf("/")).split('?')[0]).split('#')[0].substr(url.lastIndexOf("."))
}
Examples:
ext("design.swf")
ext("/design.swf")
ext("http://www.adobe.com/products/flashplayer/include/marquee/design.swf")
ext("/marquee/design.swf?width=792&height=294")
ext("design.swf?f=aa.bb")
ext("../?design.swf?width=792&height=294&.XXX")
ext("http://www.example.com/some/page.html#fragment1")
ext("http://www.example.com/some/dynamic.php?foo=bar#fragment1")
Note:
File extension is provided with dot (.) at the beginning. So if result.charat(0) != "." there is no extension.
This is the answer:
var extension = path.match(/\.([^\./\?]+)($|\?)/)[1];
Take a look at regular expressions. Specifically, something like /([^.]+.[^?])\?/.
// Gets file extension from URL, or return false if there's no extension
function getExtension(url) {
// Extension starts after the first dot after the last slash
var extStart = url.indexOf('.',url.lastIndexOf('/')+1);
if (extStart==-1) return false;
var ext = url.substr(extStart+1),
// end of extension must be one of: end-of-string or question-mark or hash-mark
extEnd = ext.search(/$|[?#]/);
return ext.substring (0,extEnd);
}
url.split('?')[0].split('.').pop()
usually #hash is not part of the url but treated separately
This method works fine :
function getUrlExtension(url) {
try {
return url.match(/^https?:\/\/.*[\\\/][^\?#]*\.([a-zA-Z0-9]+)\??#?/)[1]
} catch (ignored) {
return false;
}
}
You can use the (relatively) new URL object to help you parse your url. The property pathname is especially useful because it returns the url path without the hostname and parameters.
let url = new URL('http://www.adobe.com/products/flashplayer/include/marquee/design.swf?width=792&height=294');
// the .pathname method returns the path
url.pathname; // returns "/products/flashplayer/include/marquee/design.swf"
// now get the file name
let filename = url.pathname.split('/').reverse()[0]
// returns "design.swf"
let ext = filename.split('.')[1];
// returns 'swf'
var doc = document.location.toString().substring(document.location.toString().lastIndexOf("/"))
alert(doc.substring(doc.lastIndexOf(".")))
const getUrlFileType = (url: string) => {
const u = new URL(url)
const ext = u.pathname.split(".").pop()
return ext === "/"
? undefined
: ext.toLowerCase()
}
function ext(url){
var ext = url.substr(url.lastIndexOf('/') + 1),
ext = ext.split('?')[0],
ext = ext.split('#')[0],
dot = ext.lastIndexOf('.');
return dot > -1 ? ext.substring(dot + 1) : '';
}
If you can use npm packages, File-type is another option.
They have browser support, so you can do this (taken from their docs):
const FileType = require('file-type/browser');
const url = 'https://upload.wikimedia.org/wikipedia/en/a/a9/Example.jpg';
(async () => {
const response = await fetch(url);
const fileType = await FileType.fromStream(response.body);
console.log(fileType);
//=> {ext: 'jpg', mime: 'image/jpeg'}
})();
It works for gifs too!
Actually, I like to imporve this answer, it means my answer will support # too:
const extExtractor = (url: string): string =>
url.split('?')[0].split('#')[0].split('.').pop() || '';
This function returns the file extension in any case.
If you wanna use this solution. these packages are using latest import/export method.
in case you wanna use const/require bcz your project is using commonJS you should downgrade to older version.
i used
"got": "11.8.5","file-type": "16.5.4",
const FileType = require('file-type');
const got = require('got');
const url ='https://upload.wikimedia.org/wikipedia/en/a/a9/Example.jpg';
(async () => {
const stream = got.stream(url);
console.log(await FileType.fromStream(stream));
})();
var fileExtension = function( url ) {
var length=url.split(?,1);
return length
}
document.write("the url is :"+length);

How to get nested query string parameter

The use case is to land on a page with a URL looking like this -
http://localhost:3000/track?url=https://somewebsite.com/?968061242&lang=EN&sign=daff4be265096eb31aca5c986ac51c6c&source=api_wrapper
I tried the following to get the query params,
let search = window.location.search;
let params = new URLSearchParams(search);
let resp = params.get('url');
console.log("resp => ", resp);
but the output I get is only up to https://somewebsite.com/?968061242
How I can also get the nested params as part of the same get method call?
Use urlencoding api of JS
Example:
const url = `http://localhost:3000/track?url=${encodeURIComponent('https://somewebsite.com/?968061242&lang=EN&sign=daff4be265096eb31aca5c986ac51c6c&source=api_wrapper')}`
let search = new URL(url).search;
let params = new URLSearchParams(search);
let resp = params.get('url');

How do I remove part of a string from a specific character?

I have the following url:
http://intranet-something/IT/Pages/help.aspx?kb=1
I want to remove the ?kb=1 and assign http://intranet-something/IT/Pages/help.aspx to a new variable.
So far I've tried the following:
var link = "http://intranet-something/IT/Pages/help.aspx?kb=1"
if(link.includes('?kb=')){
var splitLink = link.split('?');
}
However this just removes the question mark.
The 1 at the end of the url can change.
How do I remove everything from and including the question mark?
Use the URL interface to manipulate URLs:
const link = "http://intranet-something/IT/Pages/help.aspx?kb=1";
const url = new URL(link);
url.search = '';
console.log(url.toString());
var link = "http://intranet-something/IT/Pages/help.aspx?kb=1"
if (link.includes('?kb=')) {
var splitLink = link.split('?');
}
var url = splitLink ? splitLink[0] : link;
console.log(url);
var link = "http://intranet-something/IT/Pages/help.aspx?kb=1"
if(link.includes('?kb=')){
var splitLink = link.split('?');
console.log(splitLink[0]);
}
You can also try like this
const link = "http://intranet-something/IT/Pages/help.aspx?kb=1";
const NewLink = link.split('?');
console.log(NewLink[0]);

get file name of selected file

How can I get only the name of the selected Data. I do the following but get the whole path of the File. I would like to display the filename for the user
var dialog = require('electron').remote.dialog;
var url;
document.getElementById('openButton').onclick = () => {
dialog.showOpenDialog((fileName) => {
if(fileName === undefined) {
alert('No file selected');
} else {
console.log(fileName)
url = fileName[0];
console.log(url);
$('#dataFileName').html(url)
}
})
};
What i get is "/Users/void/Desktop/abc.xlsx" and I would like to have in addition to that only the file i opened.
You can also use path.basename()
const {basename} = require('path')
let filePath = "/Users/void/Desktop/abc.xlsx"
let fileName = basename(filePath)
Here is a simple way you can grab just the file name:
var filePath = "/Users/void/Desktop/abc.xlsx";
var fileName = filePath.replace(/^.*[\\\/]/, '');
console.log(fileName);
Here is a fiddle to demonstrate.
If I understood correctly, you can use this:
var mystring = "/Users/void/Desktop/abc.xlsx"; //replace your string
var temp = mystring.split("/"); // split url into array
var fileName = temp[temp.length-1]; // get the last element of the array
What you basically do is to split your url with "/" regex, so you get each bit, and filename is always the last bit so you can get it with array's length you just created.

Get pathname along with PHP vars using JavaScript?

I want to save an entire URL paths to a variable, including the php vars, eg:
mysite.com/pagename?id=2
I can use
var pathname = window.location.pathname;
but this only retrieves the URL without the variables.
Is there a function to retrieve the URL as a literal string?
This should work
window.location.href
Have you tried see if it works:
document.URL
Can you try this,
// Get current page url using JavaScript
var currentPageUrl = "";
if (typeof this.href === "undefined") {
currentPageUrl = document.location.toString().toLowerCase();
}
else {
currentPageUrl = this.href.toString().toLowerCase();
}
Ref: http://www.codeproject.com/Tips/498368/Get-current-page-URL-using-JavaScript
It's hard , this answer explains how to implement it from the top response:
function getQueryParams(qs) {
qs = qs.split("+").join(" ");
var params = {}, tokens,
re = /[?&]?([^=]+)=([^&]*)/g;
while (tokens = re.exec(qs)) {
params[decodeURIComponent(tokens[1])]
= decodeURIComponent(tokens[2]);
}
return params;
}
//var query = getQueryParams(document.location.search);
//alert(query.foo);

Categories

Resources