JavaScript > Regular Expressions Modifiers

Match end characters in JavaScript

How to match any string with the specified characters at the end of a string in JavaScript?


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

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

<script>
    function mySearch() {
        var a = "crack jack trick"; 
        var b = /ck$/g; //* Matches only at the end of the string *//
        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 "crack jack trick" to the variable a, at the end of each word in a string there is a specified character 'ck', but we need to return the specified characters if it is at the end of a string, for that we are using $ quantifier in variable b. var b = /ck$/g here ck is the specified characters, $ quantifier matches the specified characters at the end 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 (/ck$/) at the end of a string with the help of a global search g and gives the output.

OUTPUT

NOTE: The output returns only one 'ck' which is at the end of a string ("crack jack trick").

 Views: 3171 | Post Order: 149



Write for us






Hosting Recommendations