Accepting an UpperCase value in Javascript [duplicate] - javascript

This question already has answers here:
How to do case insensitive string comparison?
(23 answers)
Closed 2 years ago.
I understand we need to use toUpperCase, but I wasn't sure where to put it. I would like the word "toyota" to be acceptable whether it's uppercase or lowercase.
let correctGuess = false;
let car = "toyota";
let guess = prompt ('guess the car');
if (guess === car){
correctGuess = true;
}
if (correctGuess === true){
console.log ('correct');
}
else {
console.log('incorrect')
}

Convert both of them to either uppercase or lowercase and compare.
Example:
if(guess.toLowerCase() === car.toLowerCase()) {
// your logic
}
Although you have already defined car as lowercase so you don't really need to convert it to lowercase.

Change
if (guess === car){
correctGuess = true;
}
To
if (guess.toUpperCase() === car.toUpperCase()){
correctGuess = true;
}
Kind of redundant but it gets useful if the car variable itself was taken from a user input.
You can also make both .toLowerCase to get the same result, literally no difference

Related

How to validate whether a variable is valid integer allowing +/-? in pure javascript [duplicate]

This question already has answers here:
How to check if a variable is an integer in JavaScript?
(41 answers)
Closed 3 years ago.
I need to validate whether a input is a valid integer allowing for +/- entries.
I have tried this.
function valid(elem)
{
var num = parseInt(elem);
if(!Number.isInteger(num))
{
alert ("Not an integer");
}
}
But the issue here is , it is validating even strings like 10sd as an integer. So how to validate this?
I want to validate as following:
valid(-10) = true;
valid(+10) = true;
valid(-10.01) = false;
valid(10sd) = false;
valid(10.23see) = false;
valid(10) = true;
Simple
function valid(elem){return parseInt(elem)==elem}
function valid(value) {
if(typeof value === 'number' && isFinite(value))
alert ("It is an integer");
}
This function does the job, typeof is a keyword in Javascript which tells you the data type of the variable
You can check this out, for more usage of typeof:
https://webbjocke.com/javascript-check-data-types/
Edit: made a silly error in alert, it should alert if it is an integer, the if condition checks for number

JavaScript if statements not functioning [duplicate]

This question already has answers here:
What is the correct way to check for string equality in JavaScript?
(11 answers)
Closed 4 years ago.
I'm sure there is a perfectly logical explanation to why this isn't working the way I want it to but I am new to JavaScript so would love some help. Is there any reason you would know as to why it prints out yes even when I want it to print out no.
Thanks in advance
<script type="text/javascript">
var username = prompt("What is your VC?");
if (username = "wow") {
greeting = document.write("yes");
} else {
document.write("no");
}
</script>
The = operator is used for assignment, for checking the value you can use ===.
So, change the if as follows:
if (username === "wow")
Working code is given below:
var username = prompt("What is your VC?");
if (username === "wow") {
greeting = document.write("yes");
} else
{
document.write("no");
}
Yes. One = is assignment. Two == tests equality. And three === tests strict equality.
var username = prompt("What is your VC?");
if (username === "wow") {
document.write("yes");
} else {
document.write("no");
}
When you say:
a = b
You're saying "set a to the value in b."
If you out that in an if statement's expression, it assigns b to a and thrn checks if a's new value is "truthy."
If you want to ask "is a equal to b," you have to say:
a == b
I know that there is a difference between == and ===, but I am not a JavaScript master, so I cannot tell you what the difference is!

How to remove all non-alphabet characters, javascript [duplicate]

This question already has answers here:
Java, Check if a String is a palindrome. Case insensitive
(5 answers)
Closed 5 years ago.
I am asked to check if a string is a Palindrome.
To not be case sensitive. To ignore all characters that are not letters.
My Answer
function palindrome(str) {
var oldStr = str.toLowerCase().replace(/\s+|\,|\.|\_|\-|\:|\(|\)|\/|\\/g, '');
var newStr = str.replace(/\s+|\,|\.|\_|\-|\:|\(|\)|\/|\\/g, '').split("").reverse().join("").toLowerCase();
if ( oldStr === newStr){
return true;
}
else {
return false;
}
}
palindrome("ininiNI");
The function is to be checked with any string possibility.
Example: ("0_0 (: /-\ :) 0-0") Which according to the requirements should return true.
I could not find a better solution in JavaScript then the one above.
Is there a faster/better way than just writing out each possible character to be removed/replaced? (especially since what I wrote is far from exhaustive...)
There is no need to call toLowerCase() and replace() twice. You can also cut string in a half, reverse one part and then compare. That way you can speed up your function few times at least.
Optimized function may look like that:
function palindrome(str) {
str = str.toLowerCase().replace(/[^a-z]/g, '');
var max = str.length - 1;
for (var i = Math.floor(max / 2); i >= 0; i--) {
if (str[i] != str[max - i]) {
return false;
}
}
return true;
}
palindrome("inabcbani"); //true
palindrome("abcddcba"); //true
palindrome("a*#$(b)&^#%#%(*a"); //true
palindrome("abba"); //true
palindrome("abcdba"); //false
For loop will be the fastest way in my opinion as it's quick and simple. You can return false once you find first character that doesn't match.

Dynamic insertion is not working in regular expression [duplicate]

This question already has answers here:
How do you use a variable in a regular expression?
(27 answers)
Closed 9 years ago.
I have this function
function validateUsername(str,minL,maxL){// i'm passing validateUsername("asdf_1",2,8)
var exp=new RegExp(/^[a-z0-9_-]\w{"+minL+","+maxL+"}$/);
switch(exp.test(str)){
case true: return true;
case false: return false;
}
}
I want to insert minimum Length and maximum length dynamically,
But if above code used,its giving me false whether it should accept the string as true.
can anyone tell me, what should i use rather "+variable+" to insert the value dynamically.
Thanks in advance.
You can use the regex object constructor to build your regex from a string as stated here.
Example taken from linked answer :
var re = new RegExp("a|b", "i");
// same as
var re = /a|b/i;
In your case that would do something like :
function validateUsername(str,minL,maxL){// i'm passing validateUsername("asdf_1",2,8)
var exp=new RegExp("^[a-z0-9_-]\w{" + minL + "," + maxL + "}$");
/*
why ???
switch(exp.test(str)){
case true: return true;
case false: return false;
}
*/
return exp.test(str);
}
You can separate length validation from the pattern, something like this
if(str.length<minL || str.length>maxL){
// invalid length
}else{
var exp=new RegExp(/^[a-z0-9_-]\w$/);
return exp.test(str)
}

jQuery has/ contains words [duplicate]

This question already has answers here:
How to check whether a string contains a substring in JavaScript?
(3 answers)
Closed 9 years ago.
I'd like to achieve that, if "clientpsseabq" string is contained in variable Var_words then equal true, else false. I just have no idea what method or function do I need to use?
var Var_words = "https://www.go.me/outputsearchs/clientpsseabq"
if ( Var_words contains string "`clientpsseabq`"){
return true;
}else{
return false;
}
if someone could help me how can I complete this task?
Use the (native JavaScript) function String.indexOf():
if(Var_words.indexOf('clientpsseabq') !== -1) {
return true;
} else {
return false;
}
.indexOf() returns the index of the string. If the string is not found, it returns -1.
A smaller, cleaner solution would be to simply return the value of the conditional directly:
return (Var_words.indexOf('clientpsseabq') !== -1);
You can try this
if (Var_words.indexOf("clientpsseabq") >= 0)
or with care of case sensitivity
if (Var_words.toLowerCase().indexOf("clientpsseabq") >= 0)
{
// your code
}
use a regular expression to test for the case
if(/clientpsseabq/.test(Var_words)){
//given string exists
} else {
//given string does not exists
}
if(Var_words.indexOf("clientpsseabq") >= 0))
{
}

Categories

Resources