M. AmirQ
M. AmirQ

Reputation: 61

Getting string value from url

var url = "http://www.example.com/activate_account.html#123,572ad7f557455";
var userid = url.substring(url.indexOf("#") + 1);
var pass = url.substring(url.indexOf(",") + 1);

console.log("User id: " + userid + "Password: " + pass);

I would like to get string from the URL as value but when I try javascript code like above the value has been given is not what I want. The output that I get from code above is like this:

userid : 123,572ad7f557455 pass : 572ad7f557455

The problem is the userid. How can I display only 123 before the comma?

userid : 123

Upvotes: 1

Views: 80

Answers (4)

Huy Nguyen
Huy Nguyen

Reputation: 2060

Simple way is:

var url = "http://www.example.com/activate_account.html#123,572ad7f557455";    
var urlData = url.substring(url.indexOf("#") + 1);
var userinfo = urlData.split(',');

console.log("User id: " + userinfo[0]);
console.log("Password: " + userinfo[1]);

It's work if your password in param don't have ,.

If you password have ,, use slice to make sure it work:

var url = "http://www.example.com/activate_account.html#123,572ad7f557455";
var urlData = url.substring(url.indexOf("#") + 1);
var userinfo = urlData.split(',');
var userId = userinfo[0];
var userinfo = urlData.split(',');
var userPassword = urlData.slice(userId.length + 1, urlData.length); // userId.length + 1 to remove comma

console.log("User id: " + userId);
console.log("Password: " + userPassword);

Upvotes: 1

mmuzahid
mmuzahid

Reputation: 2270

You could try to set end index for substring() method by url.indexOf(",") like this:

var userid = url.substring(url.indexOf("#") + 1, url.indexOf(","));

N.B. split() may help you if there is no , at password field.

Upvotes: 0

Ramin
Ramin

Reputation: 207

This is not the right way to send params through URL, you need to change it like http://www.example.com/activate_account.html?paramName=123 then you can get your data by param name. And also sending user name and password like this is not good at all, you need to put that in authorization header which will be encoded by base 64 for security purposes.

Upvotes: 0

Nelson Teixeira
Nelson Teixeira

Reputation: 6562

try this:

var url = "http://www.example.com/activate_account.html#123,572ad7f557455";
var params = url.substring(url.indexOf("#") + 1).split[','];    
var userid = params[0];
var pass = params[1];

console.log("User id: " + userid + "Password: " + pass);

Upvotes: 0

Related Questions