The if statement not working properly in Javascript - javascript

I am trying to create a logic that if anyone enters "<p>" and "</p>" characters inside <textarea>, then only Jquery should show the win message.I have a textarea with class html, a h2 with class result which shows win or loss.By now, I have this code:
var html = $('.html').val();
if(html.indexOf("</p>" && "<p>") === -1)
{
document.getElementById("result").innerHTML = "You lost it.";
}
else{
document.getElementById("result").innerHTML = "Hurray!You won";
}
But, this code is only checking if the <p> is there and not checking for </p>.So what can I do....

The expression "</p>" && "<p>" is equivalent to "<p>" -- && evaluates each of its arguments from left to right, and returns the last truthy argument. Since both strings are truthy, what you wrote is effectively:
if (html.indexOf("<p>") === -1)
If you want to test whether a string contains two substrings, you have to call indexOf separately for each of them:
if (html.index("</p>") !== -1 && html.indexOf("<p>") !== -1)

From MDN (Logical Operators) - Logical And (&&):
Returns expr1 if it can be converted to false; otherwise, returns
expr2. Thus, when used with Boolean values, && returns true if both
operands are true; otherwise, returns false.
</p> isn't being evaluated as false, so the second value is returned which is <p>.
This means that you're only checking for the index of <p>. Try this instead:
var html = $('.html').val();
if (html.indexOf("</p>") === -1 && html.indexOf("<p>") === -1) {
document.getElementById("result").innerHTML = "You lost it.";
}
else {
document.getElementById("result").innerHTML = "Hurray! You won";
}

.indexOf takes a single string as an argument. You cannot combine string elements together using && like that.
The simplest way to modify your code would be to make two separate checks, one for the opening tag and one for the close:
if (html.indexOf("</p>") !== -1 && html.indexOf("<p>") !== -1)
This makes two separate checks for the two strings.
Alternatively, you could create a jQuery object from the HTML fragment inside your <textarea>, then check that it has no children that are <p> tags:
if ($('<div>'+html+'</div>').find('p').length > 0) {
// the textarea contains some <p> tags
}

Related

Is there a way to clarify the true and false statements in this JS?

I've been working on learning JS, and I can't seem to figure out why my boolean values keep coming back either always true or always false.
So I believe I understand the basics of the truthy/falsy situation in JS, but I can't seem to get it right. I know that there are data type issues, (can't make different data types do different things).
function lastCharacter(char1, char2) {
if (char1[-1] === '' && char2[-1] === '') {
return true;
} else {
return false;
}
}
console.log(lastCharacter('apple', 'pumpkine'));
Or
function lastCharacter(char1, char2) {
if (char1[-1] === char2[-1]) {
return true;
} else {
return false;
}
}
console.log(lastCharacter('apple', 'pumpkina'));
Define a function lastCharacter that accepts two strings as arguments.
lastCharacter should return true if both strings end with the same character.
Otherwise, lastCharacter should return false.
They either return always true or always false. Can anyone help me?
You need a different method for getting the last character of a string, preferably with String#slice and a negative value for getting the last one. Then compare and return the result.
function lastCharacter(string1, string2) {
return string1.slice(-1) === string2.slice(-1);
}
console.log(lastCharacter('apple', 'pumpkine'));
A comparison between taking the last character of an empty string by using an index -1 which returns undefined and slice, which returns an empty string.
var x = '';
console.log('#' + x.slice(-1) + '#');
console.log('#' + x[x.length -1] + '#');
You can use slice
function lastCharacter(char1, char2) {
return char1.slice(-1) === char2.slice(-1)
}
console.log(lastCharacter('apple', 'pumpkina'));
console.log(lastCharacter('apple', 'snake'));
Or you can just access the last index
function lastCharacter(char1, char2) {
return char1[char1.length-1] === char2[char2.length-1]
}
console.log(lastCharacter('apple', 'pumpkina'));
console.log(lastCharacter('apple', 'snake'));
There are no negative array indexes in JavaScript, instead of char1[-1] you have to use char1[char1.length - 1].
Accessing one of a strings characters (e.g. "abc[1]) will always have a length of 1, it will never be equal to "". Your second function makes more sense.
Also
if(condition) { return true; } else { return false; }
is equal to
return condition;
The notation [-1] does not implicitly mean "one character from the end of the string" in JavaScript. You can use str[str.length - 1]. (If you expect possible empty source strings, you'd want to check for that too to avoid ending up with exactly the same problem.)
Instead of an if/else that returns either true or false, just return the results of the logical expression:
return char1[char1.length - 1] === '' && char2[char2.length - 1] === '';
Both the === comparisons return either true or false anyway, so the overall expression value has to be one of those. In general however if you want to make absolutely sure that you end up with a boolean, you can prefix an expression with !! to force the standard JavaScript "truthy-falsy" evaluation:
return !!(expression);

Make user input start with either "BR" or "BT"

I have an input field and I would like for it to check if the input entered starts with either "BR" or "BT". So for example BR1234 would be valid but JH1234 would not be valid. At the moment I can only get it to check "BR" and not "BT".
This is the code I have so far:
if (ID.indexOf('BR') === 0) || (ID.indexOf('BT') === 0){
}
else {
ID = "Invalid ID"
document.getElementById('ID').innerHTML = ID
return false;
Check that you have the proper parentheses in the right positions. The condition for your if statement only contains ID.indexOf('BR') === 0 because you already closed the parenthesis for it.
if (ID.indexOf('BR') === 0 || ID.indexOf('BT') === 0) {
// ...
}
You can also use String.prototype.startsWith to check if a string starts with the desired string.
if (ID.startsWith('BR') || ID.startsWith('BT')) {
// ...
}
You can use JavaScript startsWith method. Check if it helps.
Try this: if(ID.test(/^(B(R|T))/)==true){//do stuff} Remember your old friend RegExp.

If/Else Statement Returning false positives

In my code, I have this if/else statement to deal with a situation in which the numbers and letters both return cont = false. I have tried running just this code, with the same result. Obviously, it should execute the code in the else statement. Does anyone have any ideas?
var input = prompt()
if (input == null || " ") {
//Cont determines whether or not to continue
console.log("cont = false");
var cont = false;
}else{
console.log("cont = true");
var cont = true;
}
Because that code is not how you check one input against two values.
if ( input == null || " " )
should be
if (input==null || input == " ")
input == null || " "
evaluates to (result of your comparison) || " ". Now since " " (a non-empty string) is a truthy value this always evaluates to true.
For order of evaluation -
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence
Adding to the other replies which are all correct about the || operator and precedence.
Using == is not a good thing to do in most cases, not least because 0 == null etc - if you're checking if it's actually null or an empty string then something like this is safer:
if (input === null || input.trim() === "") {
...
This checks type as well as content, so won't be able to give false positives. though if input isn't a string it will complain.
Thank's so much! As a summary of all of the answers recieved so far:
The OR operator (||) is comparing input == null to " ", the latter of which always evaluates to true
=== is better than ==
Thanks again for all the help and support!

String compare in JavaScript

Can anybody help me to do string compare(means not string to string as such, the values are fetched from object and stored in variable and comparing variable to variable, variable to variable) in the JavaScript.
var val = findObject(":text1").text;
var real = findObject(":text2").text;
if (real.search(val) > 0) // if(real.indextOf(val) > -1) {
test.log("Pass");
}
else {
test.log("fail");
}
You should be able to achieve that by using the === operator
var val = findObject(":text1").text;
var real = findObject(":text2").text;
if (real === val) // if(real.indextOf(val) > -1)
{
test.log("Pass");
}
else
{
test.log("fail");
}
The === operator performs value as well as the type checking
Just compare them as follows
if (val === real){
}
else
{
}
If you know that both types are string you can also use '==' instead of '==='
Checking for exact same values is made by:
When comparing only values
==
When comparing values and types
===
When you want to check if y is a substring inside x string.
x.indexOf(y) > -1
I would recommend trim input before comparing (if that won't mess with business logic).
Like so:
var val = findObject(":text1").text.trim();
This will remove all not necesary spaces and white characters, that could be sometimes troublesome.

CoderByte SimpleSymbols challenge: pattern recognition in strings (using RegExp)

The problem:
Have the function SimpleSymbols(str) take the str parameter being passed and determine if it is an acceptable sequence by either returning the string true or false. The str parameter will be composed of + and = symbols with several letters between them (ie. ++d+===+c++==a) and for the string to be true each letter must be surrounded by a + symbol. So the string to the left would be false. The string will not be empty and will have at least one letter.
My code:
function SimpleSymbols(str) {
var arr = str.match(/[\+][a-zA-Z][\+]/g);
var total = str.match(/[a-zA-Z]/g);
if(arr === null || total === null)
return false;
else if(arr.length >= 1 && arr.length === total.length)
return true;
else
return false;
}
All the test cases except for these three pass:
-"+z+z+z+"
-"2+a+a+"
-"+z+z+==+a+"
What I've done: checked the other question on this problem. Tried another solution using regex but it had issues with input like "b".
I think the problem has something to do with when the pattern is "+char+char+" since a lot of the other test cases are like "++char+==+char+=="

Categories

Resources