JavaScript > Regular Expressions Modifiers

Match beginning characters in JavaScript

How to match any string with the specified characters at the beginning in JavaScript?


By using ^ quantifier we can match any string with the specified characters at the beginning of a string.

<p>Click the below button to match 'Au' beginning of a string.</p>
<input type="button" value="Click" onclick="mySearch()" />
<p id="myId"></p>

<script>
    function mySearch() {
        var a = "Australian came to vist Aurangabad last August";
        var b = /^Au/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 "Australian came to visit Aurangabad last August" to the variable a, in that string at the beginning of three words there is specified characters 'Au', but we need to return the specified characters if it is at the beginning of a string, for that we are using ^ quantifier in variable bvar b = /^Au/g here Au is the specified characters, ^ quantifier matches the specified characters at the beginning of a string and g do the global search, var r returns the global search result. Onclick of the button "Click" in the HTML code fires the function my Search() in the <script> block at the same time ^ quantifier matches any string with the specified characters (/^Au/) at the beginning of a string with the help of a global search g and gives the output.

OUTPUT

Note: The output returns only one 'Au' which is at the beginning of a string ("Australian came to visit Aurangabad last August").

 Views: 540 | Post Order: 150



Write for us