How to successfully break out of function in javascript? - javascript

So I have a function that checks if the last character in a string is an arithmetic operator(+,-,*,/), and if it is it should immediately return from the function. If not, the subtract sign should be appended to the string. However, only the second case seems to be occurring and I can't figure out why. If anyone could provide some insight I would be very appreciative.
$("#subtract").click(function () {
var original=$("#display").text();
var sliced=original.slice(0,original.length - 1);
var signs=["+","-","*","/"];
var charpos=sliced.charAt(sliced.length -1);
if ((charpos === signs[0]) || (charpos === signs[1]) || (charpos === signs[2]) || (charpos === signs[3])) {
return;
}
else {
var newdisplay=sliced + "-";
$("#display").text(newdisplay);
}
});

You're slicing the input which is removing the last character, then using charAt and getting the second to last character.
var original=$("#display").text(); // "foobar"
var sliced=original.slice(0,original.length - 1); // "fooba"
var charpos=sliced.charAt(sliced.length -1); // "a" -- we lost the "r"
You only need to call charAt and work with the last character (or, if you prefer slice, it's able to accept a negative number and backtrack the string).
Secondly, since signs is an array, you can use indexOf over checking each element. e.g.
var original = $('#display').text();
var signs = ["+","-","*","/"];
var lastChar = original.slice(-1); // OR original.charAt(original.length - 1);
// Check for the lastChar in the signs array
if (signs.indexOf(lastChar) != -1){ // -1 == not found
return; // short exit
}

var original=$("#display").text();
var sliced=original.slice(0,original.length - 1);
the second line gets rid of the last character in your string. so you're not even able to check what that was. just get rid of it and change the first line to
var sliced=$("#display").text();
and everything should work fine

Instead of
if ((charpos === signs[0]) || (charpos === signs[1]) || (charpos === signs[2]) || (charpos === signs[3])) {
return;
}
try
if ($.inArray(charpos, signs) > -1) {
return;
}
First of all, never enumerate items from an array in such a fashion - it's easy to miss items that way. Secondly, exact instance comparison (===) won't fire, unless you compared exact same strings.
Besides, consider revising how you extract the last character.

Related

Not understanding why in javascript my if statement is going to the wrong line

I currently have an if statement that is checking if the target is null and if the target is not null then to check if the target is not 'select... '. If it is not BOTH null and 'select... ' then I want it to execute the code. When I run this code it always skips the first line of the body of the if statement and goes to the second line. I do not understand why. In this case it always goes to targetValue = getTargetValue();
if (target != null && !(target.lastIndexOf('select... ', 0) === 0))
{
permalink.href += "&Target=" + target;
targetValue = getTargetValue();
}
I am not sure if I have a logical error or not. I am using the firefox debugger and I stepped through this code.
May be the problem is with the lastIndexOf as it searches backwards from the given index. So in your case you gave it 0 which would definitely return -1
The lastIndexOf() method returns the last index at which a given
element can be found in the array, or -1 if it is not present. The
array is searched backwards, starting at fromIndex.
Try this without any argument
if (target != null && !(target.lastIndexOf('select... ') === 0))
{
permalink.href += "&Target=" + target;
targetValue = getTargetValue();
}

checking if digit exists on particular place in string

I have a string that starts with "TT" and ends with six digits(ex. "TT012345", "TT012000, TT329001). The string is always formatted like this and I need to check if the last digit in this string is of a certain value.
Say I have the string "TT032970". In this case I'd like to get a match on this string since the last digit is zero and the digit before that is a seven(I'm looking for 7).
The string "TT037000" should also be a match but "TT0329701" shouldn't(since it isn't all zeroes to the right of the seven(the "last" 7 in the string)).
I was thinking of using a set of nested if's using substr() to check all places of the string for zeroes and if it isn't a zero in position n, then I check if the digit I'm looking for exists in position n.
My code is repetitive and I'm all for being efficient.
This is what I got so far(that works but only checks the last place of the string and the second last place):
var lastDigit = [3, 7, 8], tda = document.querySelectorAll('td a'), i, j;
function checkArray(num) {
"use strict";
for (j = 0; j < lastDigit.length; j++) {
if (num === lastDigit[j]) {
return true;
}
}
}
for (i = 0; i < tda.length; i++) {
if ((parseInt(tda[i].textContent.substr(8, 1), 10) === 0 && checkArray(parseInt(tda[i].textContent.substr(7, 1), 10))) || checkArray(parseInt(tda[i].textContent.substr(8, 1), 10))) {
tda[i].style.background = "rgb(255, 144, 255)";
amountOfTickets.push(tda[i]);
}
}
I'm positive there's a great way of checking the string for trailing zeroes and check the first non-zero digit before the zeroes. However, I'm really bad with loops and I just can't figure out how.
I'm very keen on figuring it out myself but I need a head start. I'd rather take a detailed explanation on how to do it than just the "answer".
If anything else seem off I'd gladly listen to improvements.
Thanks in advance!
To get the first digit before the zeros at the end of a string, you may use a regular expression :
+string.match(/(\d)0*$/)[1]
Example 1 :
var string = "TT032970";
var digit = +string.match(/(\d)0*$/)[1];
console.log(digit); // logs 7
Example 2 :
console.log(["TT012345","TT012000","TT329001","TT032970"].map(function(string){
return +string.match(/(\d)0*$/)[1]
})); // logs [5, 2, 1, 7]
Demonstration
Obviously, from the other answers, a regular expression will be much simpler than your loops. Moreover, any nested loop solution will be difficult to work, as you don't know how many levels deep you have to look. (Is there one zero? Two? Five?)
This regex is quite simple:
/(\d)0+$/
If you do a match on that with your string, you should get either null if it doesn't match (e.g. "TT0329701") or a two-element array if it does (e.g. "TT037000" will return ["7000", "7"].)
That should be enough for your to build your own solution upon.
Best of luck.
The first thing I though about is something like this (depends on whether I understood your problem correctly):
function lookFor(str, digit) {
//validate input...
if (str.length != 8) return false;
if (str[0] != "T" && str[1] != "T") return false;
//start at the end and move to the left as long as there are zeros
//the first non-zero element must be our digit, else return false
for (var i = str.length-1; i>0; --i) {
if (str[i] !== "0") {
return str[i] === digit;
}
}
}
lookFor("TT012000", "2") --> true
lookFor("TT012000", "3") --> false
But I guess the regex solution is probably more compact than this one.

textbox must contain number or letter validation on javascript without regex

Hi guys i got a problem here, how i can validate a password box that must contain at least one numeric character. i'm not allowed using regular expression / regex. i have tried searching over the web, but the solution is always end with regex.
here's my code that i try
function validateIn()
{
var pass=document.getElementById('password').value;
for(var i=0;i<pass.length;i++)
{
if(isNaN(pass.charAt(i))==false)
{
return true;
break;
}
else
{
return false;
}
}
}
i have tried that way but i fail, can u help me guys? thanks before
One possible approach:
function validateIn() {
var pass = document.getElementById('password').value,
p = pass.length,
ch = '';
while (p--) {
ch = pass.charAt(p);
if (ch >= '0' && ch <= '9') {
return true; // we have found a digit here
}
}
return false; // the loop is done, yet we didn't find any digit
}
The point is, you don't have to return immediately after you have found a normal character (as you're basically looking for a single digit) - you just have to move on with your checking.
Note that I have gone without isNaN, as it's a bit inefficient: the only thing required is a range check.

Javascript syntax issue

Here is my jsFiddle
Its on the Phone method, no the name one
Now is this line right? I only want it to be true if the first 3 letters are 087
var RightStarting3 = value.substring(0,2) == (087);
if (BlankPass || LessThan10 || RightStarting3 || GreaterThan10 || (HasSpaces > 0))
{
document.getElementById('Phone').style.background = "red";
return false;
}
else {
document.getElementById('Phone').style.background = "white";
document.getElementById("PhoneTick").style.visibility="visible";
return true;
}
var RightStarting3 = value.substring(0,3) === ('087');
value.substring(x) returns a string and 087 and 87 mean the same to javascript interpreter. You should change one of the datatypes so that they match...
Either the substring to an integer:
var RightStarting3 = parseInt(value.substring(0,2)) == 87;
Or the value you're comparing against to a string:
var RightStarting3 = value.substring(0,3) == "087";
Secondly -- you are invoking ValidateName() immediately (in your assignment to NamePass). Is this really necessary? There will be empty values on page load.
I think with the javascript substring(x,y) method, the y value is the value at which to stop the selection. So in your example the first 3 characters will not be selected and instead the first 2 characters will be selected.
var a = "123";
// this returns "12"
alert(a.substring(0,2));
You probably want to use var RightStarting3 = value.substring(0,3) == ('087'); instead.
KingKongFrom's answer is correct, I would add that you should make sure that value (whatever that is) isn't null first, cause if you try to call substring on null it will thrown an exception and die.

Find unique value in at least two strings

if I have 10 different strings and I want to find if at least 2 that contain some value... what would the logic be on that?
all "and's" does not work and neither does all "or's"
Below won't work...
This will only work if every one has value...
if(str1 && str2 && str3 && str4 && str5 && str6 && str7 && str8 && str9 && str10)
This will be true if there is only one value... needs to be at least 2
if(str1 || str2 || str3 || str4 || str5 || str6 || str7 || str8 || str8 || str10)
Is there any easy way to do this?
Edit: More info...
There is going to be ten long strings and I need to chunk through them and check (for instance) if any of the first characters are the same, then check if any of the second characters are the same etc. but I can add all the extra "charcode at" stuff in later. The same answer will work for checking full length strings and finding if two are the same.
Put all strings in an array say myArray and count strings having the value and see if count is greater than or equal to 2
var count = 0;
for (var index=0; index<myArray.length; index++) {
if(myArray[index].indexOf(value) != -1) {count++;}
if(count==2) break;
}
if(count==2){alert("atleast 2 have value");}
else {alert("Less than 2 have value");}
Add each string to an array and then iterate the array, incrementing a counter every time a match is found:
var val = "search string here";
var arr = [str1, str2, str3, str4, str5, str6, str7, str8, str9, str10];
var matches = 0;
for (var i = 0; i < arr.length; i++) {
if (arr[i].indexOf(val) > -1 && ++matches >= 2) break;
}
if (matches >= 2) {
alert("validates");
} else {
alert("failed");
}
It's a little unclear what you're asking. If you want to check if at least two of the strings are duplicates of each other, then the following should do:
function duplicatesExist (array) {
var hash = {};
for ( var i = 0 ; i < array.length ; i++ ) {
if ( hash.hasOwnProperty(array[i]) ) return true;
else hash[array[i]] = true;
}
return false;
}
duplicatesExist([str1, str2, str3, ...]);
Make an array containing the ten strings. Create a "nonEmptyItemCount" variable (or similar) and set it to zero. Loop through the array, testing the current item, and if it has a value increment nonEmptyItemCount. When you are done looping, see if nonEmptyItemCount >= 2
To test the number of strings that are not empty it is easy to build an array of those strings (let's call it arrayOfStrings). The number of not empty strings you can find with
arrayOfStrings.filter(function(s) { return s }).length
I hope this is what you were looking for. To explain it: filter returns all elements of the array where the function returns true. The filter function gets the string as an argument. We just return it and while javascript is coercing the value into a boolean every empty string will evaluate to false. This leaves only the not empty ones in the result. A length of the resulting array is the number you are looking for and you compare it to your wanted minimum

Categories