First, quickly understand why these two APIs are used
In the past, we had to analyze and process the URL address in the address bar, and we needed to analyze the string ourselves, for example:
https://www.zhangxinxu.com/wordpress/?s=url
If we want to know what the s
value behind the parameter is, we often need to perform character cutting and matching, or regular matching.
In fact, browsers now have a built-in API interface to process URLs, and this API is URLSearchParams()
as well URL()
.
For example, the obtained s
query parameter value can be directly as follows:
new URL('https://www.zhangxinxu.com/wordpress/?s=url').searchParams.get('s');
or:
new URLSearchParams('?s=url').get('s');
Second, let's first understand the syntax of URLSearchParams()
grammar
// URL query string var myUrlSearchParams = new URLSearchParams(strSearchParams); // query character sequence var myUrlSearchParams = new URLSearchParams(arrSearchSequence); // query key value object var myUrlSearchParams = new URLSearchParams(objSearchKeyValue);
parameter
strSearchParams
URL query string. Usage hint:
var params1 = new URLSearchParams('?s=url');
Or instantiate the query string of the current address bar address:
var params2 = new URLSearchParams(location.search);
arrSearchSequence
The query character sequence in the form of an array. E.g:
var params3 = new URLSearchParams([['s', 'url'], ['someId', 1]]);
objSearchKeyValue
The query object in the form of key-value pairs. E.g:
var params4 = new URLSearchParams({"s": "url", "someId": 2})
Three, URLSearchParams instance methods
new URLSearchParams()
The return value myUrlSearchParams
of the above execution is an instance of URLSearchParams.
This URLSearchParams instance contains many methods, as follows:
URLSearchParams.append(name, key)
Add new key-value pairs as query parameters. E.g:
var params = new URLSearchParams('?s=url'); // You can also directly without a question mark's=url' params.append('from','zxx'); // The query string at this time is:'s =url&from=zxx'
URLSearchParams.delete(name)
Delete existing query parameters. E.g:
var params = new URLSearchParams('?s=url'); params.delete('s'); // The query string at this time is:''
URLSearchParams.entries()
Return the iterator object of the query parameters, we can iterate the iterator object to get all the key-value pairs. For example, use for..of :
var searchParams = new URLSearchParams("s=url&from=zxx"); // Display all key-value pairs for (var pair of searchParams.entries()) { console.log(pair[0]+','+ pair[ 1]); }
The console input result shows:
URLSearchParams.forEach(callback)
This method can traverse the query object.
Among them callback
is the traversal method, which supports two parameters, the value and key of each key-value pair. Signal:
var searchParams = new URLSearchParams("s=url&from=zxx"); // output value and key content searchParams.forEach(function(value, key) { console.log(value, key); });
URLSearchParams.get(name)
Returns the value of the specified keyword object. E.g:
var params = new URLSearchParams('s=url&from=zxx'); params.get('s'); // The return value is:'url'
If there is no corresponding value, return null
.
URLSearchParams.getAll(name)
Returns the values corresponding to all current query keywords in the form of an array, for example:
var params = new URLSearchParams('s=url&s=urlsearchparams&from=zxx'); params.getAll('s'); // 返回值是:['url', 'urlsearchparams']
URLSearchParams.has(name)
Returns a boolean value, true
or false
whether a query keyword is included.
var params = new URLSearchParams('?s=url'); params.has('s') == true; // true
URLSearchParams.keys()
Returns an iterator object that allows iterating all the keywords in the object. Usage hint:
var searchParams = new URLSearchParams("s=url&from=zxx"); // Show all keys for (var key of searchParams.keys()) { console.log(key); }
URLSearchParams.values()
Returns an iterator object that allows iterating all key values in the object. Usage hint:
var searchParams = new URLSearchParams("s=url&from=zxx"); // Display all values for (var value of searchParams.values()) { console.log(value); }
URLSearchParams.set(name, value)
Replace if there is, crown if not. E.g:
var params = new URLSearchParams('s=url&s=urlsearchparams&from=zxx'); params.set('s','css世界'); params.getAll('s'); // The return value is: ['css世界']
You can see that all previous 's'
query parameter values will be replaced . The following example shows "nothing is crowned":
var params = new URLSearchParams('s=url'); params.set('from', 'zxx'); params.toString(); // 结果是:'s=url&from=zxx'
That is, this parameter will be added when there is no corresponding parameter.
URLSearchParams.sort()
The method sorts all the key/value pairs contained in this object in place and returns undefined
. The sort order is based on the Unicode code point of the key. This method uses a stable sorting algorithm (that is, the relative order between key/value pairs with the same key is preserved). E.g:
var searchParams = new URLSearchParams('c=4&a=2&b=3&a=1'); // key-value pair sort searchParams.sort(); // display the sorted query string console.log(searchParams.toString()) ; // The result is: a=2&a=1&b=3&c=4
URLSearchParams.toString()
Convert the URLSearchParams object into a query string. This code indicates that the above appears multiple times and will not be repeated here.
URLSearchParams() compatibility
Edge17+ support.
Fourth, let's learn about URL() syntax
The URL interface is used to parse, construct, normalize and encode URLs. The constructed instance supports several attributes and methods, which can be used to read and write URL-related attribute values. We can even present the content of the file as part of the URL.
Before using URL()
, it is recommended to judge whether the browser supports or not, for example:
if (window.URL) { // ... }
In addition, the URL interface supports use in web workers.
grammar
var myUrl = new URL(url, [base])
parameter
url
Relative address or absolute address. If it is a relative address, base
parameters need to be set , if it is an absolute address, the base
setting will be ignored . We can also use URL objects as url parameters. The value in effect at this time is the href
attribute value in the URL object .
base
If the URL address is a relative address, this parameter is required, which serves as the base address for relative calculation. We can also use the URL object as the base parameter, and the value at this time is the href
attribute value in the URL object . If this parameter is not set, it will ''
be processed as an empty string .
If the parameter value cannot be combined into a complete URL address, a TypeError error will be reported.
Test and usage indication
Basic usage indication:
var base =' https://www.zhangxinxu.com '; // The result is: https://www.zhangxinxu.com/study console.log(new URL('study', base).href); // The result is: https://www.zhangxinxu.com/study console.log(new URL('/study', base).href);
You can directly use URL objects as parameters:
var base ='https: //www.zhangxinxu.com '; var urlFromBase = new URL('study', base); // The result is: https://www.zhangxinxu.com/study console.log(new URL (urlFromBase).href); // The result is: https://www.zhangxinxu.com/wordpress console.log(new URL('wordpress', urlFromBase).href);
The following is a test with a deeper base address and different relative address forms:
var base =' https://www.zhangxinxu.com/study/a/b/c '; // The result is: https://www.zhangxinxu.com/study/a/b/sp/icon console.log (new URL('sp/icon', base).href); // The result is: https://www.zhangxinxu.com/study/a/b/sp/icon // The comparison of the upper and lower results shows that ./ and nudity There is no difference in relative addresses console.log(new URL('./sp/icon', base).href); // The result is: https://www.zhangxinxu.com/study/a/sp/icon // Up One level of URL level depth console.log(new URL('../sp/icon', base).href); // The result is: https://www.zhangxinxu.com/study/a/b/sp/ icon // The level is calculated according to the slash console.log(new URL('../sp/icon', base +'/').href); // The result is: https://www.zhangxinxu.com /sp/icon // The beginning of the slash indicates that the address starts to match console.log(new URL('/sp/icon', base).href);
Seeing is believing, the following is the console output:
The following is a test between different domain names:
var base ='https ://www.zhangxinxu.com '; // The result is: http://image.zhangxinxu.com and https://image.zhangxinxu.com // URLs without agreement are considered relative addresses, The protocol is taken from the base address console.log(new URL('//image.zhangxinxu.com','http://www.zhangxinxu.com').href); console.log(new URL('//image. zhangxinxu.com',' https://www.zhangxinxu.com ').href); // The result is: https://image.zhangxinxu.com // Here url is the complete absolute address, so ignore the following base parameter console.log(new URL('https://image.zhangxinxu.com', base).href);
This is the result after running:
Here is the test that failed:
// If there is no absolute address, an error will be reported console.log(new URL('').href); console.log(new URL('//image.zhangxinxu.com').href);
V. Properties and methods of URL instance objects
The return value of new URL() is an instance object, including the following properties and methods.
Attributes
The known URL addresses are as follows:
var url = new URL('https://www.zhangxinxu.com:80/wordpress/?s=url#comments'); var ftp = new URL('ftp://username:[email protected]/path/file');
hash
The anchor chain value in the URL address contains a string '#'
, for example url.hash
, the return value here is '#comments'
.
host
The host host address in the URL address, including the protocol port number, url.host
the return value here is 'www.zhangxinxu.com:80'
.
hostname
The host name in the URL address does not include the port number. url.hostname
The return value here is 'www.zhangxinxu.com'
.
href
The completed URL address.
origin [read only]
The source of the returned URL address will include the URL protocol, domain name and port. url.origin
The return value here is 'https://www.zhangxinxu.com:80'
.
password
Returns the password before the URL address domain name. It is more common in the ftp protocol. ftp.password
The return value here is 'password'
.
username
Returns the username before the domain name of the URL address. It is more common in the ftp protocol. ftp.username
The return value here is 'username'
.
pathname
Return the directory + file name in the URL. For example ftp.pathname
, the return value here is '/path/file'
.
port
Returns the port number in the URL address. For example , the return value here url.port
is '80'
, ftp.port
the return value is ''
.
protocol
Return the protocol of the URL address, including the colon after it ':'
. For example , the return value here url.protocol
is 'https:'
, ftp.protocol
the return value is 'ftp:'
.
search
Returns the query string of the URL address. If there are parameters, the return value starts with a question mark '?'
. For example url.search
, the return value here is '?s=url'
.
searchParams
Return a URLSearchParams object, you can call various methods of the URLSearchParams object, and process the query string very conveniently. For example, if we want to know s
the value corresponding to the query keyword , we can:
url.searchParams.get('s');
method
toString()
You can understand the returned complete URL address as another form of URL.href, but this can only be output, and the value cannot be modified.
toJSON ()
It also returns the complete URL address, and the returned string is the href
same as the attribute.
Static method
URL.createObjectURL(object)
You can turn a File, Blob or MediaSource object into a unique blob URL. The parameters object
can be File, Blob or MediaSource objects.
URL.revokeObjectURL(objectURL)
Undo the previously URL.createObjectURL()
created URL object. The parameter objectURL
represents the URL.createObjectURL()
return value of the URL created before .
An actual use case of the static method. When
we use Ajax to request a cross-domain image to avoid the problem of canvas cross-domain generation, we can use these two static methods:
var xhr = new XMLHttpRequest(); xhr.onload = function () { var url = URL.createObjectURL(this.response); var img = new Image(); img.onload = function () { // At this point you are You can use canvas to do whatever you want with img // ... code ... // Remember to release the memory after the picture is used up URL.revokeObjectURL(url); }; img.src = url; }; xhr.open('GET', url, true); xhr.responseType ='blob'; xhr.send();
compatibility
Edge 12+ support.
Six, these two JS API polyfill
It can be seen from the compatibility table that URLSearchParams is only supported in Edge 17, and URL is only supported in Edge 12. It seems that the compatibility is not good, but this does not prevent us from using it in actual projects. Why? Because there are polyfills.
Here is a URL and URLSearchParams polyfill project that has been supported to the latest ES7 specification: https://github.com/lifaon74/url-polyfill
According to the official statement, it is compatible with IE 10+.
Does IE9 support it, or is it only partially supported? I roughly tested it briefly and concluded as follows:
Basic use of IE9 except for the URL() static methods is supported!
For me, enough is enough.
Update if other details are found in the actual application in the future.
Seven, conclusion
The web, whether it’s CSS, HTML or JS API, is constantly improving. It is standard and cross-platform. Many methods and features that need to be customized in the past are now natively supported by browsers. The value of the previous language frameworks is getting lower and lower. .
It's time to start trying to embrace the original, study hard and accumulate, simple and easy realization, product-oriented, user-oriented, and based on the future, before we can cross the long river.
Those friends who consulted my front-end questions, don't need to ask me any questions about Vue and React. I have never used them, nor will I use them in the future. It is not my direction, nor the future direction.