1

I have the following encoded URL string in javascript

var querystring = "http%3A%2F%2Fspsrv%3A1361%2FSitePages%2FCountryManagment%2Easpx%3FCountryId%3D1";

How can I get the value of CountryId from that ?

3
  • A number put instead CountryId? Commented Sep 14, 2016 at 12:04
  • How did you encode the URL? Commented Sep 14, 2016 at 12:06
  • what do you mean ? Commented Sep 14, 2016 at 12:06

2 Answers 2

1

You will need to decode the URL with decodeURIcomponent and then use regex to get the parameter from URL

var querystring = decodeURIComponent("http%3A%2F%2Fspsrv%3A1361%2FSitePages%2FCountryManagment%2Easpx%3FCountryId%3D1");
document.getElementById("decodedURL").innerHTML = querystring;
function getParam(param, url) {
    if (!url) url = window.location.href;
    param = param.replace(/[\[\]]/g, "\\$&");
    var regex = new RegExp("[?&]" + param + "(=([^&#]*)|&|#|$)"),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return results[2].replace(/\+/g, " ");
}
document.getElementById("parameter").innerHTML = getParam("CountryId", querystring);

Demo: JSFIDDLE

Sign up to request clarification or add additional context in comments.

3 Comments

@user6599525 - No problem. Hope you can now continue with what you want to achieve
Your solution is long while simpler way exist.
@Mohammad I know there is simpler ways, this was the way I know. So I gave my answer just the same as you did. There was no need for this comment from you. You answered and I gave an answer aswell.
1

At first, you should decode url, using .decodeURI() you can do it. Then you can use .split() to spliting URL to array or use .match() to selecting specific part of URL by regex.

var querystring = "http%3A%2F%2Fspsrv%3A1361%2FSitePages%2FCountryManagment%2Easpx%3FCountryId%3D1";

var result = decodeURIComponent(querystring).split("?")[1].split("=")[1];
var result2 = decodeURIComponent(querystring).match(/CountryId=([\d]+)/)[1];

console.log(result, result2);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.