JavaScript > Regular Expressions Modifiers

Finding digits in JavaScript

How to find any digit between the brackets in JavaScript?


By using [0-9] Expression we can find any digit between the brackets.

<p>Click the below button to find any digit between the brackets.</p>
<input type="button" value="Click" onclick="mySearch()" />
<p id="myId"></p>

<script>
    function mySearch() {
        var a = "54789614597822347";
        var b = /[3-7]/g;
        var r = a.match(b);
        document.getElementById("myId").innerHTML = r;
    }
</script>

In the above code snippet we have given Id as "myId"to the second <p> element in the HTML code. There is a function mySearch() in the<script>block which is connected to the Onclick of the HTML button and there is a string with value "54789614597822347" to the variable a, from the string we need to find the digits between the brackets [3-7] for that we are using [0-9] expression in the variable b. var b = /[3-7]/g, in this code g do the global search for the digits between the brackets [3-7]. Variable r returns the mentioned digits between brackets from a string. Onclick of the button "Click" in the HTML code fires the function mySearch() in the <script> block, at the same time [0-9]expression finds the digits between the brackets {[3-7]} from a string with the help of global search and returns the output.

OUTPUT

 Views: 592 | Post Order: 143



Write for us