JSFiddle - React, Tailwind, and code Playground

by justinw

JavaScript

var req = "?ID=&Total=2&StartDate=2013-01-01&FinishDate=2013-01-07&Status=Fail";

// Extract a particular key's value from the source
function extractQueryString(source) {
  var oResult = {};
  var aQueryString = source.split("&");
  
  for (var i = 0; i < aQueryString.length; i++) {
    var aTemp = aQueryString[i].split("=");
    if (aTemp[1].length > 0) {
      oResult[aTemp[0]] = unescape(aTemp[1]);
    }
  }
  
  return oResult;
}

// Update the key's value in source.  If key is not found, append it to the source
function updateQueryString(source, key, value) {
   var re = new RegExp("([?|&])" + key + "=.*?(&|$)", "i");
   var separator = source.indexOf('?') !== -1 ? "&" : "?";
  
   if (source.match(re)) {
     return source.replace(re, '$1' + key + "=" + value + '$2'); 
   } else {
     return source + separator + key + "=" + value;
   }
}

// Examples
var oData = extractQueryString(req);
document.write('<p>' + oData.StartDate + '</p>');

var oQuery = updateQueryString(req, 'Status', 'OK');
document.write('<p>' + oQuery + '</p>');