Why cant I add var in if statement - javascript

I'm trying to run a simple program to teach my friend to code:
var name = prompt("Whats your name");
if name = "Jason" {alert ("your name is Jason");
but for some reason it just wont let me ad the variable "name". What should I do?

I think you need
if (name === "Jason") { /*Do something */}
Rather than the single equals. Double/triple equals compares whereas single equals sets.

Related

how can you take out extra space in Javascript?

I'm trying to give a welcome message to recruiters that view my html webpage. The javascript code I'm using is:
function myFunction() {
var person = prompt("Please enter your name", "");
if (person == null) {
var message = document.getElementById("demo").innerHTML =
"Hello! Thank you for viewing my resume.";
message.innerHTML.replace((/\s/g,''));
}
else {
document.getElementById("demo").innerHTML =
"Hello " + person + "! Thank you for viewing my resume.";
}
}
The output in the html looks like Hello ! Thanks for viewing my resume. I've tried flipping the else and if outputs but it still adds the extra space. How can I fix this? I know there are similar questions on stack but the solutions haven't worked in my case. Thanks for your help.
in this case I think you can use Template literals (Template strings), one feature of ES6.
function myFunction() {
const person = prompt("Please enter your name", "");
if (!person) {
const message = document.getElementById("demo").innerHTML =
"Hello! Thank you for viewing my resume.";
message.innerHTML.replace((/\s/g,''));
}
else {
document.getElementById("demo").innerHTML =
`Hello ${person}! Thank you for viewing my resume.`;
}
}
The input would be labeled as Undefined which does not necessarily equal Null in JavaScript. My advice would be try creating a different way to check the name. Perhaps just give them the option "Continue as Guest" instead of checking for an empty value.
message.innerHTML.replace((/\s/g,''));
That line is doing absolutely nothing, replace() returns a new string, it doesn't modify the old one
And even if it replaced the old one, the desired output wouldn't really be what you're looking for, it would remove all spaces in the string, all of them.
The way you remove extra spaces is by using .trim(), trim() removes any extra spaces at the start and/or at the end of the string, so you would do: message.innerHTML = message.innerHTML.trim();
if (person == null) {
This wouldn't work, since prompt would return an empty string if the user didn't provide anything and your explicitly checking if it is equal to null instead, the most "optimal" way for checking for that, is as #Anh Tuan did, if (!person), this works because empty strings, undefined, or null all are falsy, so this is a nice way to check for all of them.
use:
if (!person)
instead of:
if (person == null)
and it should work fine. Everything else can stay the same.

Using regex to test out of 4 words in an array has a perfect match

I was tasked with a project of creating a CV site were the user uploads a .docx file and the details is extracted from the file and is automatically inputted in the template designed by me,
I have been able to extract the details .docx file with JavaScript and the extracted details was kept in an array to make it easy to identify words with indexing. For example
[Adeola Emmanuel, adeolaemmanuel#gmail.com, pharmacist, 2 ketu ikorodu lagos, etc].
where i need help is not all CV uploaded by the user has the name coming first or email coming second but its sure that they come within 0,6 of the array so i decided to write a function that will help with that but its not working
var email = email(text.slice(0, 5));
function email(email) {
var re = /.{1,}#[^.]{1,}/ig;
if (!re.test(email)) {
email = text.slice(0, 1);
return email;
} else if (re.test(email)) {
email = text.slice(3, 5);
return email;
}
}
You can use the find array method:
function getEmail(arr) {
let re = /\S#[^.\s]/;
return arr.find(str => re.test(str));
}
let text = ["Adeola Emmanuel", "adeolaemmanuel#gmail.com", "pharmacist", "2 ketu ikorodu lagos"];
let email = getEmail(text.slice(0, 5));
console.log(email);
Some remarks:
{1,} in regular expressions can be shortened to just +
You actually don't need to test for multiple occurrences with +, since you would already accept one occurrence. So that also means you would be OK with just one non-point character after the #.
Neither of the regex suffixes (ig) have any use in your regex.
The .test method should get a string as argument, not an array. So you need to pass it email[0] for example.
For a full test of whether some string is a valid email address, the regular expression would be way more complex
When an if condition is false, there is no need to test the exact opposite in the else block: by exclusion that opposite condition will always be true when it gets executed.
The slice of an array is still an array, so returning text.slice(3, 5); in the else block does not make sense. You want to return a string.
You need a loop to inspect other array elements for as long as you don't have a match and have not reached the end of the array. So some loop construct is needed. You can use for, while, or any of the array methods that do such looping. find is particular useful in this case.
Don't give your function the same name as another variable (email) as only one value can be assigned to that variable (a function, a string, or still something else). So in your case you'll lose the function definition by the var initialisation.

How to check and remove extra white spaces from a string during condition check

if (userResponseField.value.toUpperCase().includes('MY NAME IS ') === true || userResponseField.value.toUpperCase().includes('MY NAME\'S ') === true) {
What I am basically trying to do is create some sort of chatbot and it's working perfectly, it's just that it gets confused by extra whitespaces. How can I remove them during the condition check? I've looked for answers but none of them worked with the condition, they are still correct though, just not working with the way I want to do this whole thing. Note: I don't want the condition to make changes to the string/variable itself.
You could use regex:
if (userResponseField.value.match(/my\s+name(\s+i|')s/gi))
This returns true for inputs such as ' My name is '.
let predicate = str => !!str.match(/my\s+name(\s+i|')s/gi);
[
'my NaME iS ',
'my NaME\'s',
'my name s',
'my ame is',
'my nameis',
].forEach(input => console.log(input, ':', predicate(input)));
Have a look on trim :
if (
userResponseField.value.toUpperCase().trim().includes('MY NAME IS') === true ||
userResponseField.value.toUpperCase().trim().includes('MY NAME\'S') === true
) {
You can use String.prototype.trim() on both the value and the hard-coded string:
var userResponseField = {};
userResponseField.value = 'MY NAME IS';
if (userResponseField.value.toUpperCase().trim().includes('MY NAME IS '.trim()) === true || userResponseField.value.toUpperCase().trim().includes('MY NAME\'S '.trim()) === true) {
console.log("true");
}
it's me again.
I found a clever way to do this and if some of you, in the future, have this problem and have just found this thread, here is how I solved my problem:
var userResponseFieldOutput = userResponseField.value;
userResponseField.value = userResponseField.value.replace(/\s+/g, ' ');if
Since this code, along with the condition I have posted above are stored in a function, the userResponseFieldOutput is what I am going to use for outputting the user's messages in the chatbox. It remains unedited, while the userResponseField.value has its spaces removed.
For example:
chatResponse(userResponseFieldOutput, "Hi, " + userName);
Ignore the userName variable, it is part of the code that doesn't have to be shown right now. This is another function I have made, the first value is what appears in the chat on the right side, where the user's responses are shown. The string and the variable after the comma are what appears on the left side of the chat, where the chatbot's messages are shown. But as you can see, I don't use userResponseField.value. Instead, I am using userResponseFieldOutput, which will print the user's output without the extra white spaces being removed.
I hope I have been useful to all of you who are looking for a solution to this problem.

Javascript: why to declare the same value of the same variable twice?

I want a prompt appear and ask user to type in a correct password. And every time user types in the wrong pw, the prompt should re-appear. I don't understand why the following code wouldn't work:
var secret = prompt("What is the password?");
while ( secret !== "sesame" ) {
secret;
}
document.write("Welcome.");
If "secret" is a global variable then inside the while loop it should be interpreted as having the value of prompt("What is the password?")?
But it turns out that I should write secret = prompt("What is the password?");inside the while loop:
var secret = prompt("What is the password?");
while ( secret !== "sesame" ) {
secret = prompt("What is the password?");
}
document.write("Welcome.");
Why to declare the same value of variable secret twice?
A line of code that is simply secret; does nothing - it merely references, but does nothing with, a variable named secret.
What you mean to do is:
var secret;
while(secret !== 'secretpassword') secret = prompt("What's the password?");
For the first iteration of the loop secret does not equal the secret password, so the prompt is run. And it will run repeatedly until the correct one is entered.
However, there's a lot of problems with your approach.
Firstly, ever-lasting dialog windows (of which a prompt is a kind) are not very UI friendly; they necessarily demand focus so you can't click away from them without interacting with them. What if the user wanted to dismiss the prompt and click a "forgot pass" link or use some other part of the page?
Secondly, storing a password in JavaScript is a massive and obvious security risk, but I'll assume this is a tutorial or homework of some kind where the focus is not on security.
Thirdly, document.write() is long-ago deprecated and there's almost no use for it these days. Look instead into DOM-scripting.
When you assign an expression in a variable, the variable only contains the value returned by that expression, not the expression itself
Therefore, evaluating the variable won't have any effect, and won't evaluate the assigned expression again.
If you don't want to repeat the function call, you can use a do while loop
var secret;
do {
secret = prompt("What is the password?");
} while ( secret !== "sesame" );
But of course, JS passwords are useless

Checking if words match with or without spaces

I have a code, I'll just give a small example below. Though what it does is gets the users name, then checks for other context. Then I check them versus eachother, and my entire script works besides this one point and it's not giving a leeway.
var getName= $('#element').text(),
uName =getName.replace("Welcome ",""),
loggedIn = newMember.replace(membersList,"");
if(loggedIn !== uName)
{
//run other codes
}
Though when I do this it's still running the code. Am I writing the conditional wrong?
From your question title, I assume your concern is that the string comparison of loggedIn !== uName is being impacted by leading and/or trailing spaces on one or the other.
You need to use trim(), and would be wise to validate the presence of the prototype before using it (see this answer for an explanation).
Your code would now be:
if(!String.prototype.trim) {
String.prototype.trim = function () {
return this.replace(/^\s+|\s+$/g,'');
};
}
var getName= $('#element').text(),
uName =getName.replace("Welcome ","").trim(),
loggedIn = newMember.replace(membersList,"").trim();
if(loggedIn !== uName)
{
//run other codes
}

Categories

Resources