简体   繁体   中英

Javascript Greater than or less than

I did a rewrite of the code I submitted yesterday based on suggestions from others. I now have this but still can't seem to get it to work with greater than less than. I can add/substract the 2 numbers and get a valid answers. I can't get a > < to work however. Hoping someone can offer some additional help keeping it within this format of "If statements".

if ((input.search("what is greater")!= -1) && (input.search(/\d{1,10}/)!=-1) && (input.search(/\d{1,10}/)!=-1)) 
{var numbersInString = input.match(/\d+/g); 
var num1 = parseInt( numbersInString[0], 10 ); 
var num2 = parseInt( numbersInString[1], 10 ); 
if (num1 < num2) document.result.result.value = ""+num1+" is less than "+num2+""; 
if (num1 > num2) document.result.result.value = ""+num1+" is greater than "+num2+""; 
if (num1 = num2) document.result.result.value = "Both numbers are equal"; 
return true;}

It sounds like you want to manipulate a number in two ways:

1) You want to refer to the individual characters.

2) You want to compare the number to another number and see if one is greater than another.

If you have a string called input , then you can use the function parseInt(input, 10) to convert it from a string to the number represented by that string.

If you want to get just the first two characters, you can use the substring function.

The important thing to keep in mind is that to the computer, the string '12345' and the number 12345 are completely different. The computer has a completely different set of operations that it will perform on each.

also, @albin is correct to point out that putting semicolons after your if statements is wrong.

The output of the match method is an array of strings, so I think you are NOT comparing numbers but strings. Try doing this before comparing your numbers.

var num1 = parseInt( numbersInString[0], 10 );
var num2 = parseInt( numbersInString[1], 10 );

And then compare num1 and num2.

http://jsfiddle.net/qt3RW/ Simple input box: ​​​​

<input id="input1" value="Is 6 greater than 5"></input>

Parser find 'Is # greater than #' where # is digit and alert this digits:

var IsStringValid = $("#input1").val().match(/Is \d greater than \d/g);
alert(IsStringValid);
if(IsStringValid){
    var values = $("#input1").val().match(/\d/g);
    for(var i = 0; i < values.length; i++){
        alert(values[i])
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM