[javascript] Parse URL Queries Parameter

 Q. Parse URL Queries Parameter

e.g.
Target Url List:
targetUrlList = [

https://www.youtube.com/watch?v=FbqBv7Tz1QY&list=RDFbqBv7Tz1QY&start_radio=1&ab_channel=%E5%91%A8%E6%9D%B0%E5%80%ABJayChou’,

'http://www.mysite.com/processDoc?type=word&type=pdf&type=excel&author=peter&pages=50',

];


expect output:
OutputList = [ 

{

  ab_channel: "周杰倫JayChou",

  list: "RDFbqBv7Tz1QY",

  start_radio: "1",

  v: "FbqBv7Tz1QY"

},

{

  author: "peter",

  pages: "50",

  type: ["word", "pdf", "excel"]

},

];


Answer:

function getUrlParamsToMap(url = '') {

  const queriesMap = {};

  const [baseUrl, queriesString] = url.split('?');

  const queryItems = queriesString ? queriesString.split('&') : [];

  queryItems.forEach(queryItem => {

    const [key, value] = queryItem.split('=');

    const convertedValue = decodeURIComponent(value);

    const convertedKey = decodeURIComponent(key);

    if (!queriesMap[convertedKey]) {

      queriesMap[convertedKey] = convertedValue;

    } else if (Array.isArray(queriesMap[convertedKey])) {

      queriesMap[convertedKey].push(convertedValue);

    } else {

      queriesMap[convertedKey] = [queriesMap[convertedKey], convertedValue];

    }

  });

  return queriesMap;

}


Online demo link

https://jsbin.com/zexikas

留言

熱門文章