How to extract a string from the extractd url using js or jquery?
2 Answers
With substring function, which gets the caracters between the indexes supplied
For example, if you are navigating in http://stackoverflow.com/questions,
alert(location.href.substring(7, 20))
will show "stackoverflow"
I saw you asked a similar question before, if you explain why you need to do this, we could help you better
2 Comments
jagrti
say the url is http:localhost:8080/Sample/ex1/sample1.jsp?cuId=U113&pid=123, now i have to captute the cuId and pid. .
Pavel Hodek
@jagrti: I think, my answer is working solution. Maybe it should be accepted.
You can use Regular Expression to parse URL - see http://www.javascriptkit.com/jsref/regexp.shtml
var re = /(http.?):\/\/([^\/]*)\/(.*)/
var url = 'http://stackoverflow.com/questions/5814008/qts-on-javascript-jquery';
var tokens = url.match(re);
var theWholeUrl = tokens[0];
var protocol = tokens[1]
var domain = tokens[2];
var partAfterDomain = tokens[3];
alert('theWholeUrl: ' + theWholeUrl);
alert('protocol: ' + protocol)
alert('domain: ' + domain);
alert('partAfterDomain: ' + partAfterDomain);
Another example based on your comment:
var url = 'http://localhost:8080/Sample/ex1/sample1.jsp?cuId=U113&pid=123&anotherKey=anotherValue'
var re = /.+?cuId=(.*)&pid=([^&]*)/;
var tokens = url.match(re);
var cuId = tokens[1];
var pid = tokens[2];
alert('cuId: ' + cuId);
alert('pid: ' + pid);