String compare in JavaScript - 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.

Related

convert number to string returns empty if number 0

Trying to convert string to a number, works fine apart from when the number is zero it returns an empty string;
I understand 0 is false, but I just need a neat way of it returning the string "0"
I'm using:
const num = this.str ? this.str.toString() : '' ;
I even thought of using es6 and simply ${this.str} but that didn't work
Because 0 is "false-y" in JavaScript, as you've already figured out, you can't utilized it in a conditional. Instead, ask yourself what the conditional is really trying to solve.
Are you worried about null / undefined values? Perhaps this is better:
const num = (typeof this.str !== "undefined" && this.str !== null) ? this.str.toString() : "";
Odds are you really only care if this.str is a Number, and in all other cases want to ignore it. What if this.str is a Date, or an Array? Both Date and Array have a .toString() method, which means you may have some weird bugs crop up if one slips into your function unexpectedly.
So a better solution may be:
const num = (typeof this.str === "number") ? this.str.toString() : "";
You can also put your code in a try catch block
const num = ''
try {
num = this.str.toString();
} catch(e) {
// Do something here if you want.
}
Just adding to given answers - if you do:
x >> 0
you will convert anything to a Number
'7' >> 0 // 7
'' >> 0 // 0
true >> 0 // 1
[7] >> 0 // 7
It's a right shift bit operation. You can do magic with this in many real life cases, like described in this article.
In my case, the zero (number) that I wanted to converted to a string (which was the value of an option in a select element) was a value in an enum.
So I did this, since the enum was generated by another process and I could not change it:
let stringValue = '';
if (this.input.enumValue === 0) {
stringValue = '0';
} else {
stringValue = this.input.enumValue.toString();
}

How to check 2 different types of things using ===?

I want to check whether the value in an input box is equal to a variable. When I use ===, it returns false but when I use ==, it returns true, provided both are equal.
<input id="g1"></input> <button id="b" onclick="myFunction()">Try</button>
function myFunction() {
var d1;
d1 = Math.floor(Math.random()*100)
if( document.getElementById("g1").value == d1) {
document.getElementById("d").innerHTML = "Correct";
}
This happens because JavaScript == can compare numeric strings to numbers whereas === does not.
Similarly the "value" property your using returns a string that you're comparing to an integer. You'll need to use parseInt to convert the value first.
parseInt(document.getElementById("g1").value) === d1
A few things to consider with parseInt:
parseInt returns NaN when you try to convert non-number strings (i.e. converting 'bogus' returns NaN.
It will convert decimals into integers by dropping the decimals. So parseInt('2.1') == 2 // => true.
Honestly, given your use case, it's appropriate to use ==, but I'd add a comment explaining why it's being used.
=== means both value has to be equals but have same type of data in it aswell where == means they only needs to be equal. so for example if d1 is a string holding value 2 and g1 is an integer also holding value 2 using === would not work and will return false as both data is different even though they have same syntax.
<input id="g1"></input> <button id="b" onclick="myFunction()">Try</button>
function myFunction() {
var d1 = 0;
d1 = Math.floor(Math.random()*100)
if( paseint(document.getElementById("g1").value) === d1) {
document.getElementById("d").innerHTML = "Correct";
}
== is the equality operator
=== is an identity operator
For example true==1 is true because true is converted to 1 and then it's compared. However, true===1 is false. This is because it does not do type coercion.
That aside, in your case I think you want to try casting your value to an integer and then compare.
var string5 = '5'
var numb5 = 5
if (string5 == numb5) will return true
if (string5 === numb5) will return false
second variant also compares type, because string is not same type as number it is false.

unexpected results in evaluation of chains logical expressions javascript

I am writing a program to identify special numbers according to the criteria laid out in this code wars kata:
http://www.codewars.com/kata/catching-car-mileage-numbers
Here is a link to my full code and tests:
http://www.codeshare.io/UeXhW
I have unit tested my functions which test for each of the special number conditions and they appear to be working as expected. However, I have a function:
function allTests(number, awesomePhrases){
var num = number.toString().split('');
// if any criteria is met and the number is >99 return true
return number > 99 && (allZeros(num) || sameDigits(num) || incrementing(num) || decrementing(num) || palindrome(number) || matchPhrase(number, awesomePhrases)) ? true : false;
}
which determines if any of the criteria of being a special number is met and that's not working as expected. For example, when I tested the allZeros() function on 7000 it returned true, but alltests(7000) is returning false. Is there something about how chains of logical expressions are evaluated that I don't understand or is the problem something else?
I have looked at W3schools and MDN to try and diagnose the problem.
Change all your !== to != will do.
False results as long as allTests() executes with a second argument even it it's the empty string, as follows:
allTests(7000,"");
If the function is called with just one argument, i.e. the number, expect this error:
Uncaught TypeError: Cannot read property 'length' of undefined
The error message refers to one of the functions in the logic chain, namely matchPhrase() which expects two parameters: number and awesomePhrases. If instead of providing an empty string, you use null, you'll also get the same error message.
JavaScript doesn't support the concept of default parameters -- at least not in a way that one might expect; the parameters default to undefined. But there is a way to work around this hurdle and improve the code so that one may avoid this needless error. Just change matchPhrase() as follows:
function matchPhrase(number, awesomePhrases){
awesomePhrases = typeof awesomePhrases !== 'undefined' ? awesomePhrases : "";
for(var i = 0, max=awesomePhrases.length; i < max; i++){
if(number == awesomePhrases[i]){
return true;
}
}
return false;
}
The first statement accepts the second argument's value as long as it is not the undefined value; if so, then the variable gets set to the empty string. (Source for technique: here).
To make the code more readily comprehensible, I suggest rewriting allTests() as follows, so that the code follows a more explicit self-documenting style:
function allTests(number, awesomePhrases){
var arrDigits = number.toString().split('');
// if any criteria is met and the number is >99 return true
return number > 99 && (allZeros( arrDigits ) || sameDigits( arrDigits ) || incrementing( arrDigits ) || decrementing( arrDigits) || palindrome(number) || matchPhrase(number, awesomePhrases)) ? true : false;
}
This function takes a number and uses its toString() method to convert the number to a string. The resulting string which is not visible will split itself on the empty string so that the result of arrDigits is an array of numerical strings, each one consisting of just one digit. This is the point of origin for the ensuing problem with allZeros() which compares a stringified digit with a number.
Incidentally, in the function allTests() there is an awfully lengthy ternary expression. The syntax is fine, but you might wish to rewrite the code as follows:
function getCriteriaStatus(arrDigits,number,awesomePhrases) {
var criteria = new Array();
criteria[0] = allZeros( arrDigits );
criteria[1] = sameDigits( arrDigits );
criteria[2] = incrementing( arrDigits );
criteria[3] = decrementing( arrDigits);
criteria[4] = palindrome(number);
criteria[5] = matchPhrase(number, awesomePhrases);
var retval = false;
for (var i=0, max=6; i < max; i++) {
if ( criteria[i] == true ) {
retval = true;
break;
}
}
return retval;
}
function allTests(number, awesomePhrases){
var arrDigits = number.toString().split('');
var criteria_met = getCriteriaStatus(arrDigits,number,awesomePhrases);
return (number > 99 && criteria_met);
}
To obtain the desired true result from allTests() when it invokes allZeros(), rather than complicate the code by using parseInt(), I suggest rewriting allZeros() and any other functions containing code that compares a numerical string value with a number by changing from the identity operator to the equality operator. The change involves merely replacing === with == as well as replacing !== with !=. The code that compares values of the same data type, using the identity operators, those operators may, and probably should, remain unchanged. (See here).

indexOf is not working in JavaScript

I am checking an index Of string in JAVASCRIPT. and this is coming as false. where as the value does belong to it as below :
if(idOfControl.indexOf(idOfButton)) == is giving false for the below values.
idOfControl = "dlInventory_btnEditComment_0"
idOfButton = "dlInventory_btnEditComment"
But if I run idOfControl.replace(idOfButton, ""); It is working and replacing the text.
Any reason for this?
indexOf can also return 0, in the event of your string being found at the position 0. 0 evaluates to false. Try:
if(idOfControl.indexOf(idOfButton) > -1)
More info: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf
There are these three big options:
indexOf > -1
The result of indexOf can be 0 meaning that the string was found at the beginning of the string. When string is not found, the return value is -1, therefore:
if (idOfControl.indexOf(idOfButton) > -1) {
// Do something
}
Which can be nicer written as #paxdiablo commented:
if (idOfControl.indexOf(idOfButton) >= 0) {
// Do something
}
via regex
You can use a very simple regular expression to test your match.
var idOfControl = "dlInventory_btnEditComment_0"
var control = /dlInventory_btnEditComment/;
if (idOfControl.test(control)) {
// do something
}
This approach can be enhanced to capture the last number of your string (if you need it)
var idOfControl = "dlInventory_btnEditComment_0"
var control = /dlInventory_btnEditComment_(\d+)/;
var match = control.exec(idOfControl);
if (match) {
alert('the number found is: ' + match[1]);
}
You can try it out here: http://jsfiddle.net/4Z9UC/
via indexOf in a hacky way
This uses a bitwise operator to return a truthy value when the position is !=-1 (In two's complement notation, -1 is internally represented as 111...111, and its inversion is 000...000 which is 0, i.e. a falsy value). It is in fact more efficient than the >-1 option, but it is harder to read and to understand. (EDIT: this became so popular that you can say it is a standard)
if (~idOfControl.indexOf(idOfButton)) {
// do something
}

Exact value of two variables need to be compared in JQuery

I have the following piece of code:
$j('#row1').find('span.grpid').each(function() {
groupIdNew = groupId.split("~")[0];
var value = $j(this).html();
if (value.match(groupIdNew)){
$j(this).parents('tr').remove();
}
});
Problem is I need the value to exactly equal groupIdNew. (Eg: test_11 should not match test_1 as is the case with .match(), but exactly equal test_11). How do I do this?
Use the double equals sign?
if (value == groupIdNew) {
Use the triple if you want to be strict about the data types.
Don't use match, just compare them:
if(value === groupIdNew){
Or if you need to trim whitespace:
if($j.trim(value) === groupIdNew){
You can use if(value === groupIdNew){
you can use the triple if you want to be strict about the data type
You can just do it using the equal operator (===):
if (value === groupIdNew){
Here's the full code:
$j('#row1').find('span.grpid').each(function() {
groupIdNew = groupId.split("~")[0];
var value = $j(this).html();
if (value === groupIdNew){
$j(this).parents('tr').remove();
}
});
use === operator
if (value === groupIdNew){
$j(this).parents('tr').remove();
}

Categories

Resources