1. Obtain all parameters and convert them into JSON /object formats
/** Get all arguments *@returns json/object
*/
function getQueryString() {
// Define the return result
const result: { [key: string]: any } = {};
// Get url parameters (use decodeURIComponent to decode URL parameters)
const search = decodeURIComponent(window.location.search);
consttempArr = search ! = =' ' ? search.substr(1).split('&') : [];
tempArr.forEach((item) = > {
if (item) {
// Split the parameter name and parameter value
const itemArr = item.split('=');
// The parameter name is used as key, and the parameter value is value
result[itemArr[0]] = itemArr[1]; }});return result;
}
Copy the code
Example: URL: 'http://www.example.com?name= name &Sex= male &age=18' Call: getQueryString(); Result: {name: 'name ', Sex:' male ', age: '18'}Copy the code
2. Obtain the specified parameters
/** Gets the specified argument *@paramName Parameter name (case insensitive) *@returns string* /
function getQueryString(name: string) {
// Get url parameters (use decodeURIComponent to decode URL parameters)
let search = decodeURIComponent(window.location.search).replace('? '.' ');
consttempArr = search ! = =' ' ? search.split('&') : [];
// Change the parameter name to lowercase and retain the original case
tempArr.forEach((item) = > {
if (item) {
const itemArr = item.split('=');
search = search.replace(itemArr[0], itemArr[0].toLowerCase()); }});// Matches the specified argument
const reg = new RegExp(` (^ | &)${name.toLowerCase()}) = (/ ^ & * (& | $) `);
const result = search.match(reg);
returnresult ! =null ? result[2] : ' ';
}
Copy the code
Example: URL: 'http://www.example.com?Name=Abc&sex= male &age=18' Call: getQueryString('name'); // Case insensitive returns result: 'Abc' // Results keep original caseCopy the code
Tips: The above code is written in TypeScript, ES6.
PS: If there is any error or can be optimized in the code, please comment and correct it. Learn together and grow together.