danrodi
danrodi

Reputation: 296

Check for user in JavaScript

I have this piece of code, which checks the address bar for the string ?user=:

if(window.location.href.indexOf("?user=") > -1) {
    start();
} else {
    alert("No user.");
}

But actually I would like to check, if the ?user= has something after it, for example a name. I would be glad if you could help me out.

Upvotes: 0

Views: 62

Answers (3)

m1.
m1.

Reputation: 1325

You could just use this regular expression:

/user=\w+(&|$)/.test(window.location.search)

Upvotes: 0

ArrayKnight
ArrayKnight

Reputation: 7356

var user = (window.location.search.match(/user=(\w+)/) || [])[1];

if(user) {
    start();
} else {
    alert('No user.');
}

Upvotes: 0

Barmar
Barmar

Reputation: 780861

Use a regular expression match.

if(window.location.href.match(/\?user=[^&]/) {
    start();
} else {
    alert("No user.");
}

Upvotes: 3

Related Questions