I am just starting to learn location API(s), such as redirection URL in javascript and I can not understand the following three lines,
Can someone explain me?
let windowUrl = new URLSearchParams(window.location.search);
const queryString = window.location.href;
const firstParam = queryString.substring(queryString.lastIndexOf("?") + 1).split("=")[0];
The first line is useless. As you can see, windowUrl never gets used.
The following two lines:
window.location.href is nothing but the URL that you see in your browser's location bar. Say, https://www.youtube.com/watch?v=123456
so queryString = "https://www.youtube.com/watch?v=123456"
what the 2nd line does is to take everything that comes after "?" in that string. So v=123456
Then, it splits v=123456 by "=" as a separator. So, finally you get 123456.
Now, all of the above is quite barbaric, as you could obtain the value that "v" parameter this way:
let url = new URL(window.location.href);
let v = url.searchParams.get("v");
URL is an interface that will, shall we say "analyze" a URL and give you methods to parse it conveniently, such as the searchParams method, and more.
MDN https://developer.mozilla.org/en-US/docs/Web/API/URL
Description inline the code:
// for Example: https://stackoverflow.com/questions/69835761/js-url-location-can-someone-explain?search=hello
windowUrl = new URLSearchParams(window.location.search);
// URLSearchParams object that helps you to provide data to the query url
// window.location.search will return the current search query from your url
queryString = window.location.href;
// the current url: in this case: https://stackoverflow.com/questions/69835761/js-url-location-can-someone-explain?search=hello
firstParam = queryString.substring(queryString.lastIndexOf("?") + 1).split("=")[0]
// you filter or prase the value from the query string
But you can have it easier, like #resle already wrote.
// get the current url
const uri = new URL(window.location.href);
const quersValue = uri.searchParams.get("search");
// output : hello
let windowUrl = new URLSearchParams(window.location.search) ==> fetching URL params from the url. E.g website.com/?hello=1
const queryString = window.location.href; ===> getting the URL of your current page.
const firstParam = queryString.substring(queryString.lastIndexOf("?") + 1).split("=")[0]; ===> String manipulation to get the first param from the URL. Would open dev tool and play with it, to get the feeling.
E.g:
const x = "https://stackoverflow.com/questions/69835761/js-url-location-can-someone-explain/?hello=1"
const x = "https://stackoverflow.com/questions/69835761/js-url-location-can-someone-explain/?hello=1"
console.log(x)
Result: 'hello'
So here's a breakdown of what the code does:
let windowUrl = new URLSearchParams(window.location.search);
Here an instance of a URLSearchParams object which parses the search (effectively the query string).
const queryString = window.location.href;
This grabs the href (i.e. the entire URL including the query string and hash) and names it queryString (very bad name)
const firstParam = queryString.substring(queryString.lastIndexOf("?") + 1).split("=")[0];
This grabs the variable named "queryString" which is the href and finds the last index of ? which the code author hoped would designate the place where the query string starts (which is not correct). It then does some string manipulation to attempt get the first query string parameter key which would probably work for most cases but not all.
This code can be greatly simplified to:
const firstParam = (new URL(window.location.href)).searchParams.keys()?.[0];
This will use the JS URL class to parse the URL correctly and get the first key of the search parameters. ?.[0] is the optional chaining operator for arrays
Note that the 3rd line is wrong in this case because a URL like https://example.com/test?param=a&other=b¶m=c#hashwith?questionmark
is valid but the code will think the first URL parameter is questionmark instead of param which would be the expected answer.
I have some urls and I want to add the string ".webp" in the alphanumeric id just before the parameter &size
http://r.rp-static.pre/r/dsn-icon?dsn=xjfhob38jg8g&size=g&v=20210314224102
http://r.rp-static.pre/r/dsn-icon?dsn=caucp0d8ig8o&size=g&v=20210309074045
http://r.rp-static.pre/r/dsn-icon?dsn=9guq9t6e5fs1&size=g&v=20210318114201
I only get these strings so I have to add ".webp" somehow with javascript.
I want this result:
http://r.rp-static.pre/r/dsn-icon?dsn=xjfhob38jg8g.webp&size=g&v=20210314224102
http://r.rp-static.pre/r/dsn-icon?dsn=caucp0d8ig8o.webp&size=g&v=20210309074045
http://r.rp-static.pre/r/dsn-icon?dsn=9guq9t6e5fs1.webp&size=g&v=20210318114201
how can I do it? Thanks
let temp = "http://r.rp-static.pre/r/dsn-icon?dsn=xjfhob38jg8g&size=g&v=20210314224102"
console.log(temp.slice(0, temp.indexOf("&size")) + ".webp" + temp.slice(temp.indexOf("&size")))
You can store the url first in a variable and then use slice to update the url.
console.log('http://r.rp-static.pre/r/dsn-icon?dsn=xjfhob38jg8g&size=g&v=20210314224102'.replace(/&size/, '.webap&size'))
let a ='http://r.rp-static.pre/r/dsn-icondsn=xjfhob38jg8g&size=g&v=20210314224102'
//your url
let url = a.replace('&size', '.webp&size');
//new url 'http://r.rp-static.pre/r/dsn-icon?dsn=xjfhob38jg8g.webp&size=g&v=20210314224102'
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("/");
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.
For example, assuming that x = filename.jpg, I want to get filename, where filename could be any file name (Let's assume the file name only contains [a-zA-Z0-9-_] to simplify.).
I saw x.substring(0, x.indexOf('.jpg')) on DZone Snippets, but wouldn't x.substring(0, x.length-4) perform better? Because, length is a property and doesn't do character checking whereas indexOf() is a function and does character checking.
Not sure what would perform faster but this would be more reliable when it comes to extension like .jpeg or .html
x.replace(/\.[^/.]+$/, "")
In node.js, the name of the file without the extension can be obtained as follows.
const path = require('path');
const filename = 'hello.html';
path.parse(filename).name; //=> "hello"
path.parse(filename).ext; //=> ".html"
path.parse(filename).base; //=> "hello.html"
Further explanation at Node.js documentation page.
If you know the length of the extension, you can use x.slice(0, -4) (where 4 is the three characters of the extension and the dot).
If you don't know the length #John Hartsock regex would be the right approach.
If you'd rather not use regular expressions, you can try this (less performant):
filename.split('.').slice(0, -1).join('.')
Note that it will fail on files without extension.
x.length-4 only accounts for extensions of 3 characters. What if you have filename.jpegor filename.pl?
EDIT:
To answer... sure, if you always have an extension of .jpg, x.length-4 would work just fine.
However, if you don't know the length of your extension, any of a number of solutions are better/more robust.
x = x.replace(/\..+$/, '');
OR
x = x.substring(0, x.lastIndexOf('.'));
OR
x = x.replace(/(.*)\.(.*?)$/, "$1");
OR (with the assumption filename only has one dot)
parts = x.match(/[^\.]+/);
x = parts[0];
OR (also with only one dot)
parts = x.split(".");
x = parts[0];
I like this one because it is a one liner which isn't too hard to read:
filename.substring(0, filename.lastIndexOf('.')) || filename
You can perhaps use the assumption that the last dot will be the extension delimiter.
var x = 'filename.jpg';
var f = x.substr(0, x.lastIndexOf('.'));
If file has no extension, it will return empty string. To fix that use this function
function removeExtension(filename){
var lastDotPosition = filename.lastIndexOf(".");
if (lastDotPosition === -1) return filename;
else return filename.substr(0, lastDotPosition);
}
In Node.js versions prior to 0.12.x:
path.basename(filename, path.extname(filename))
Of course this also works in 0.12.x and later.
I don't know if it's a valid option but I use this:
name = filename.split(".");
// trimming with pop()
name.pop();
// getting the name with join()
name.join('.'); // we split by '.' and we join by '.' to restore other eventual points.
It's not just one operation I know, but at least it should always work!
UPDATE: If you want a oneliner, here you are:
(name.split('.').slice(0, -1)).join('.')
This works, even when the delimiter is not present in the string.
String.prototype.beforeLastIndex = function (delimiter) {
return this.split(delimiter).slice(0,-1).join(delimiter) || this + ""
}
"image".beforeLastIndex(".") // "image"
"image.jpeg".beforeLastIndex(".") // "image"
"image.second.jpeg".beforeLastIndex(".") // "image.second"
"image.second.third.jpeg".beforeLastIndex(".") // "image.second.third"
Can also be used as a one-liner like this:
var filename = "this.is.a.filename.txt";
console.log(filename.split(".").slice(0,-1).join(".") || filename + "");
EDIT: This is a more efficient solution:
String.prototype.beforeLastIndex = function (delimiter) {
return this.substr(0,this.lastIndexOf(delimiter)) || this + ""
}
Another one-liner:
x.split(".").slice(0, -1).join(".")
Here's another regex-based solution:
filename.replace(/\.[^.$]+$/, '');
This should only chop off the last segment.
Simple one:
var n = str.lastIndexOf(".");
return n > -1 ? str.substr(0, n) : str;
The accepted answer strips the last extension part only (.jpeg), which might be a good choice in most cases.
I once had to strip all extensions (.tar.gz) and the file names were restricted to not contain dots (so 2015-01-01.backup.tar would not be a problem):
var name = "2015-01-01_backup.tar.gz";
name.replace(/(\.[^/.]+)+$/, "");
var fileName = "something.extension";
fileName.slice(0, -path.extname(fileName).length) // === "something"
If you have to process a variable that contains the complete path (ex.: thePath = "http://stackoverflow.com/directory/subdirectory/filename.jpg") and you want to return just "filename" you can use:
theName = thePath.split("/").slice(-1).join().split(".").shift();
the result will be theName == "filename";
To try it write the following command into the console window of your chrome debugger:
window.location.pathname.split("/").slice(-1).join().split(".").shift()
If you have to process just the file name and its extension (ex.: theNameWithExt = "filename.jpg"):
theName = theNameWithExt.split(".").shift();
the result will be theName == "filename", the same as above;
Notes:
The first one is a little bit slower cause performes more
operations; but works in both cases, in other words it can extract
the file name without extension from a given string that contains a path or a file name with ex. While the second works only if the given variable contains a filename with ext like filename.ext but is a little bit quicker.
Both solutions work for both local and server files;
But I can't say nothing about neither performances comparison with other answers nor for browser or OS compatibility.
working snippet 1: the complete path
var thePath = "http://stackoverflow.com/directory/subdirectory/filename.jpg";
theName = thePath.split("/").slice(-1).join().split(".").shift();
alert(theName);
working snippet 2: the file name with extension
var theNameWithExt = "filename.jpg";
theName = theNameWithExt.split("/").slice(-1).join().split(".").shift();
alert(theName);
working snippet 2: the file name with double extension
var theNameWithExt = "filename.tar.gz";
theName = theNameWithExt.split("/").slice(-1).join().split(".").shift();
alert(theName);
Node.js remove extension from full path keeping directory
https://stackoverflow.com/a/31615711/895245 for example did path/hello.html -> hello, but if you want path/hello.html -> path/hello, you can use this:
#!/usr/bin/env node
const path = require('path');
const filename = 'path/hello.html';
const filename_parsed = path.parse(filename);
console.log(path.join(filename_parsed.dir, filename_parsed.name));
outputs directory as well:
path/hello
https://stackoverflow.com/a/36099196/895245 also achieves this, but I find this approach a bit more semantically pleasing.
Tested in Node.js v10.15.2.
Though it's pretty late, I will add another approach to get the filename without extension using plain old JS-
path.replace(path.substr(path.lastIndexOf('.')), '')
A straightforward answer, if you are using Node.js, is the one in the first comment.
My task was I need to delete an image in Cloudinary from the Node server and I just need to get the image name only.
Example:
const path = require("path")
const image=xyz.jpg;
const img= path.parse(image).name
console.log(img) // xyz
This is where regular expressions come in handy! Javascript's .replace() method will take a regular expression, and you can utilize that to accomplish what you want:
// assuming var x = filename.jpg or some extension
x = x.replace(/(.*)\.[^.]+$/, "$1");
You can use path to maneuver.
var MYPATH = '/User/HELLO/WORLD/FILENAME.js';
var MYEXT = '.js';
var fileName = path.basename(MYPATH, MYEXT);
var filePath = path.dirname(MYPATH) + '/' + fileName;
Output
> filePath
'/User/HELLO/WORLD/FILENAME'
> fileName
'FILENAME'
> MYPATH
'/User/HELLO/WORLD/FILENAME.js'
This is the code I use to remove the extension from a filename, without using either regex or indexOf (indexOf is not supported in IE8). It assumes that the extension is any text after the last '.' character.
It works for:
files without an extension: "myletter"
files with '.' in the name: "my.letter.txt"
unknown length of file extension: "my.letter.html"
Here's the code:
var filename = "my.letter.txt" // some filename
var substrings = filename.split('.'); // split the string at '.'
if (substrings.length == 1)
{
return filename; // there was no file extension, file was something like 'myfile'
}
else
{
var ext = substrings.pop(); // remove the last element
var name = substrings.join(""); // rejoin the remaining elements without separator
name = ([name, ext]).join("."); // readd the extension
return name;
}
I like to use the regex to do that. It's short and easy to understand.
for (const regexPattern of [
/\..+$/, // Find the first dot and all the content after it.
/\.[^/.]+$/ // Get the last dot and all the content after it.
]) {
console.log("myFont.ttf".replace(regexPattern, ""))
console.log("myFont.ttf.log".replace(regexPattern, ""))
}
/* output
myFont
myFont
myFont
myFont.ttf
*/
The above explanation may not be very rigorous. If you want to get a more accurate explanation can go to regex101 to check
\..+$
\.[^/.]+$
We might come across filename or file path with multiple extension suffix. Consider the following to trim them.
text = "/dir/path/filename.tar.gz"
output = text.replace(/(\.\w+)+$/,"")
result of output: "/dir/path/filename"
It solves the file extension problem especially when the input has multiple extensions.
Another one liner - we presume our file is a jpg picture >> ex: var yourStr = 'test.jpg';
yourStr = yourStr.slice(0, -4); // 'test'
x.slice(0, -(x.split('.').pop().length + 1));
name.split('.').slice(0, -1).join('.')
that's all enjoy your coding...
I would use something like x.substring(0, x.lastIndexOf('.')). If you're going for performance, don't go for javascript at all :-p No, one more statement really doesn't matter for 99.99999% of all purposes.