1.

When is the comma operator useful in JavaScript?

Answer»

To validate decimal numbers in JavaScript, you can use regular expressions for matching with the match() method:

Let’s SAY we have the following decimal with string representation:

var val = "5.9";

The following regular expression you can use: 

var reg = /^[-+]?[0-9]+\.[0-9]+$/;   var res = val.match( reg );

For validation, we USED the above regular expression and test it using the match() method. It gives us whether the given value is decimal or not:

<html>    <body>       <script>         var val = "5.9";          var reg = /^[-+]?[0-9]+\.[0-9]+$/;            var res = val.match( reg );          if(res)            document.write("Decimal!" );          else            document.write("Not a decimal!" );       </script>    </body> </html>

The output displays ‘decimal’ since the if statement is TRUE:

Decimal!

Let us see another EXAMPLE with a DIFFERENT input i.e. a number:

<html>    <body>       <script>         var val = "7";          var reg = /^[-+]?[0-9]+\.[0-9]+$/;            var res = val.match( reg );          if(res)            document.write("Decimal!" );          else            document.write("Not a decimal!" );       </script>    </body> </html>

The output is ‘not a decimal!’, since the if statement is false:

Not a decimal!

Let us see another example and check for string:

<html>    <body>       <script>         var val = "abc";          var reg = /^[-+]?[0-9]+\.[0-9]+$/;            var res = val.match( reg );          if(res)            document.write("Decimal!" );          else            document.write("Not a decimal!" );       </script>    </body> </html>

The output displays ‘not a decimal!’ since the if statement is false:

Not a decimal!


Discussion

No Comment Found