JavaScript > Regular Expressions Modifiers

Global search in JavaScript

How to do a global search for a specified character in a string in JavaScript?


Global search

Global search is an search in JavaScript, which can be done by using regular expression g modifier.

Regular expression is nothing but an object which describes a pttern of characters.

Global search in a string.

<p>Click the below button to do case global seacrh.</p>
<input type="button" value="Click" onclick="mySearch()" />
<p id="myId"></p>

<script>
    function mySearch() {
        var a = "TechFunda is a sister concern of DotNetFunda";
        var b = /Fun/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 code which is connected to the Onclick of the HTML button.

A string with value "TechFunda is a sister concern of DotNetFunda" to the variable a, from the string we need to do a global search for a character 'Fun' in a string,  for that we are using g modifier in the variable b, variable r returns the global search result. 

Onclick of the button "Click" in the HTML page fires the function mySearch() in the script code, at the same time g modifier do the global search for a character 'Fun' in a string and returns the output.

OUTPUT

 Views: 9730 | Post Order: 139



Write for us






Hosting Recommendations