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.
Use a regular expression match.
if(window.location.href.match(/\?user=[^&]/) {
start();
} else {
alert("No user.");
}
var user = (window.location.search.match(/user=(\w+)/) || [])[1];
if(user) {
start();
} else {
alert('No user.');
}
You could just use this regular expression:
/user=\w+(&|$)/.test(window.location.search)
Related
how to write simple if take the first expression. Example bellow, my code is looks like to much.
i mean first condition email.val() and second !validateEmail(email.val()) with or expression. my big question is how to detect that first or second condition is executed ?
if(email.val() == "" || !validateEmail(email.val())){
//call the condition again
if(email.val() ==""){
$("#error").html("<p>Email Cant be empty</p>");
$("#error").show();
setTimeout(function(){$("#error").fadeOut();}, 2000)
}else{
$("#error").html("<p>Wrong email format</p>");
$("#error").show();
setTimeout(function(){$("#error").fadeOut();}, 2000)
}
email.focus();
}
so I don't need to call this if again
if(email.val() == ""){
$("#error").html("<p>Email Cant be empty</p>");
$("#error").show();
setTimeout(function(){$("#error").fadeOut();}, 2000)
}else{
$("#error").html("<p>Wrong email format</p>");
$("#error").show();
setTimeout(function(){$("#error").fadeOut();}, 2000)
}
Personally I do that way.
It allow in future to add other errors message or easy change them if needed.
// separate messages values to avoid long texts in the nested if part
// and prevent them from being searched for in parts of code
// where they can be scattered in several places, and possibly repeated
const errorMessage =
{ email_empty : '<p>Email Cant be empty</p>'
, email_wrong : '<p>Wrong email format</p>'
}
var messageError = ''
if(email.val()==='') { messageError = errorMessage.email_empty }
else if ( !validateEmail(email.val())) { messageError = errorMessage.email_wrong }
if (messageError) {
$("#error").html(messageError)
$("#error").show()
setTimeout(function(){$("#error").fadeOut();}, 2000)
email.focus()
}
You have roughly
if (condition1 || condition2) {
if (condition1) {
foo();
} else {
bar();
}
moo();
}
The else can only trigger when condition1==false and condition2==true, hence you can write the same as
if (condition1) {
foo();
moo();
} else if (condition2) {
bar();
moo();
}
So, as I see you're validating an email, there are two options you can look to avoid the nested if-else block or basically repeating your code again.
User Regex Expression: You can validate email, and check if it's empty as well.
if(!regexPat1.test(email)) {
// Do something
}
if(!regexPat2.test(email)) {
// Do something
}
Use nest condition : With this you can avoid rewriting same condition again.
if(email.val().trim() !=="") {
if(!validateEmail(email.val().trim()) {
//Throw invalid email error
}else {
// Do something
}
}else {
// Trow empty value error
}
There can be better solutions as well but I think this solves your doubt.
Simple rearrangement of your existing code.
if(email.val() == "") {
$("#error").html("<p>Email Cant be empty</p>");
$("#error").show();
setTimeout(function(){$("#error").fadeOut();}, 2000);
email.focus();
} else if (!validateEmail(email.val()) {
$("#error").html("<p>Wrong email format</p>");
$("#error").show();
setTimeout(function(){$("#error").fadeOut();}, 2000);
email.focus();
}
as said on title, validating the prompt if is null (inpname variable) inside the func/while/try wont work. output = {}
meanwhile the testing i did outside works fine.
check the code below please. what did i do wrong?
//works
let test = prompt("testing","aasdasd");
if (test === null) {
console.log("cancel");
}
else {
console.log("ok");
}
let inpname;
//do not work
let func = () => {
while (true) {
try {
inpname = prompt("name ", "name here");
if (inpname.length > 10 || inpname.length <= 3) {
throw "Your name must be at least 10 characters long, but not less than 4";
}
else if ( inpname != inpname.match(/^[a-zA-Z]+$/)) {
throw "A-Z characters accepted only!";
}
//problem here!
else if (inpname === null) {
throw "cant cancel";
}
else {
console.log("success");
break
}
}
catch (err) {
console.log(err);
break
}
}
}
func();
The console outputting {} instead of the exception seems to be a bug in Stack-snippets. You would get more correct output using console.error.
That being said, the issue you're seeing is in part caused because you're not checking that impname is null before you attempt to dereference it.
Changing the ordering of your error checking would solve the problem (Although stack-snippets is still not going to report exceptions as they happen, which is not the behavior you get in a browser)
let func = () => {
while(true) {
var inpname = prompt("name ", "name here");
try {
if (inpname === null) {
throw "cant cancel";
}
if (inpname.length > 10 || inpname.length <= 3) {
throw "Your name must be at least 10 characters long, but not less than 4";
}
if (inpname != inpname.match(/^[a-zA-Z]+$/)) {
throw "A-Z characters accepted only!";
}
return inpname;
} catch(err) {
console.error(err);
}
}
}
func();
Note that you might want to avoid disallowing use of the "cancel" button. If the user doesn't want to provide the requested info, simply exit the app with an appropriate message
I want to repeat the code until the user gets the no. right. How do I do this ?
This is the code:-
function getRandomNumber(min,max){
return Math.floor(Math.random()*(max - min + 1 ))+min;
}
randomNumber=(getRandomNumber(1,10));
input=prompt("Please enter a no. between 1 and 10:","");
if(input==randomNumber){
console.log("Good Work");
}else{
console.log("not matched");
}
You could either use a while loop that calls a "break" statement once the user inputs the correct answer, or you could use a function like this:
function getInput(){
input=prompt("Please enter a no. between 1 and 10:","");
if(input==randomNumber){
console.log("Good Work");
}else{
consol.log("not matched");
getInput(); //Gets the user's input again
}
}
Here you go...
Found needs to be set to false before you start, otherwise the function will only run one. There is little point having the function definition inside the while loop, since it will be created as a global variable.
var found = false;
function getRandomNumber(min,max) { return Math.floor(Math.random()*(max - min + 1 ))+min; }
while ( found != true ) {
var randomNumber = getRandomNumber(1,10);
console.log('Random Number is..',randomNumber);
var input = prompt("Please enter a no. between 1 and 10:","");
if ( input == randomNumber ) {
alert('Well Done')
found = true;
} else {
console.log("not matched");
}
}
I am trying to validate zip codes using an if function with a regex. Can this be done? I currently just have the if function making sure the zip code is 5 numbers.
below is the regex i want to use
(^\d{5}(-\d{4})?$)|(^[ABCEGHJKLMNPRSTVXY]{1}\d{1}[A-Z]{1} *\d{1}[A-Z]{1}\d{1}$)
Can someone show me where and how i would add this to the if function below?
var value = $(this).val();
if( value.length<5 || value==$(this).attr('id') ) {
$(this).addClass('error');
error++;
} else {
$(this).addClass('valid');
}
var ZipCode = "(^\d{5}(-\d{4})?$)|(^[ABCEGHJKLMNPRSTVXY]{1}\d{1}[A-Z]{1} *\d{1}[A-Z]{1}\d{1}$)";
if (ZipCode.test(98800)) {
// true
} else {
// false
}
Try this
Try this
var filter = "(^\d{5}(-\d{4})?$)|(^[ABCEGHJKLMNPRSTVXY]{1}\d{1}[A-Z]{1} *\d{1}[A-Z]{1}\d{1}$)";
if (!filter.test($(this).attr('id').value)) {
$(this).addClass('error');
error++;
}
else
{
$(this).addClass('valid');
}
I have this javascript and I get the error "function expected". I can't see anything wrong with my javascript. Please help. Thanks.
function checkrewardname()
{
var my=document.getElementById("Rname");
var con=my.value;
var mine=document.getElementById("forref").value.split('\n');
if (con == "")
{
alert("Enter a Reward Name.");
}
else
{
var i=0;
while(i<=mine.length)
{
if (mine(i) == con)//error here
{
alert("Duplicate reward. Please enter a new reward.");
}
else
{
document.getElementById("validate").click();
alert("The reward has been saved.");
}
i++;
}
}
}`
mine is an array but you are calling it as if it were a function. Use mine[i] rather than mine(i) and you'll access the array by index rather than generating an error. (Just a note; most C-style languages use [ and ] for array access and reserve ( and ) for function invocation).
You also have while(i<=mine.length)
shouldn't it be while(i < mine.length)