-2

I am trying to extract a specific ID from the url I have.

https://myhost.com/ReferredSummary.aspx?PolicyId=4807307&EndorsementId=5941939&EditExisting=true&NewClient=true&Adjustment=True

the ID I need is = 4807307 It always have the strings PolicyId= before and &EndorsementId= after.

How Can I extract the the from the url.

2 Answers2

0

Use split to split on = then split on & to get the value

var a='https://myhost.com/ReferredSummary.aspx?PolicyId=4807307&EndorsementId=5941939&EditExisting=true&NewClient=true&Adjustment=True';
console.log(a.split('=')[1].split('&')[0])
ellipsis
  • 12,049
  • 2
  • 17
  • 33
0

A generic function like this should be able to get any parameter

function getUrlParameter(parameterName) {
  return new RegExp(parameterName + "=([^&]+)", "i").exec(document.URL)[1];
}

So a call like getUrlParameter("policyid") should do the trick.

This is current case insensitive, If you want the parameter to exactly match the paramter then instead use return new RegExp(parameterName + "=([^&]+)").exec(document.URL)[1]

Here is a snippet you can test:

var testUrl = "https://myhost.com/ReferredSummary.aspx?PolicyId=4807307&EndorsementId=5941939&EditExisting=true&NewClient=true&Adjustment=True";

var selectElement = document.querySelector("#select"),
  resultElement = document.querySelector("#result");

// Adds parameters to select
testUrl.substring(testUrl.indexOf("?") + 1).split("&").forEach(function(param) {
  var newOption = document.createElement("option");
  newOption.textContent = newOption.value = param.substring(0, param.indexOf("="));
  selectElement.appendChild(newOption);
});

// Adds listener to select
selectElement.addEventListener("input", updateResult);
updateResult();

function updateResult() {
  resultElement.textContent = getUrlParameter(selectElement.selectedOptions[0].value);
}

function getUrlParameter(parameterName) {
  return new RegExp(parameterName + "=([^&]+)", "i").exec(testUrl)[1];
}
<select id="select"></select>
<span id="result"></span>
nick zoum
  • 7,216
  • 7
  • 36
  • 80