0

I have a URL string in JavaScript below ex- URL-"/MyProject/Information/EmpDetails.aspx?userId=79874&countryId=875567"

Now, I need to do below 2 things

  1. Check whether the country exists in above url or not and there will be only one countryId in above url

  2. Get the countryId value means 875567.

Thanks Guys for such good response quickly .I got the solution most of the answers are correct.

One More Question Guys I have hyperlink so i am generating some activities when onmousedown event .but the issue is it fires even when i do right click only..but i want the event which fires only on clicking the hyperlink double click or right click and then click

user2147163
  • 87
  • 1
  • 4
  • 13

6 Answers6

1

Fetch URL using

window.location.href

And

Split with '?' first, '&' next and '=' so that you can get countryId

OR

directly split with '=' and get last value from array that we get after split

krishna
  • 154
  • 7
0

How about something like this:

var TheString = "/MyProject/Information/EmpDetails.aspx?userId=79874&countryId=875567";

var TheCountry = parseInt(TheString.split('=').pop(), 10);

And then you just need to test if TheCountry is something with if (TheCountry) { ...}

This of course assumes that the URL query string will always have the country ID at the end.

frenchie
  • 51,731
  • 109
  • 304
  • 510
0

You need to use a combination of indexOf() and substring()

var ind = url.indexOf("countryId");
if (ind  != -1){
    // value is index of countryid plus length (10)
    var countryId = url.substring(ind+10);
}else{
    //no countryid
}
Niki van Stein
  • 10,564
  • 3
  • 29
  • 62
0
var url ='/MyProject/Information/EmpDetails.aspx?userId=79874& countryId=875567';
alert((url.match(/countryId/g) || []).length);
alert(url.substring(url.lastIndexOf('=')+1));

you can get the count of the occurrence of any string in first alert and get the countryid value by substring.

rollo
  • 305
  • 3
  • 14
0

This will convert your url query into an object

var data = url.split('?')[url.split('?').length - 1].split('&').reduce(function(prev, curr){
    var fieldName = curr.split('=')[0]; 
    var value = curr.split('=').length > 1 ? curr.split('=')[1] : '';
    prev[fieldName] = value; 
    return prev
}, {});

then you can just check the value of data.country to get the value

Titus Popovici
  • 149
  • 2
  • 11
0

You may also split the string and see if the countryId exists, as below.

var myString = "/MyProject/Information/EmpDetails.aspx?userId=79874&countryId=875567";
myString = myString.split("countryId="); //["/MyProject/Information/EmpDetails.aspx?userId=79874&", "875567"]
if (myString.length === 2) {
    alert (myString.pop());
}
lshettyl
  • 8,166
  • 4
  • 25
  • 31