JavaScript > Placing JavaScript code

Finding characters in string in JavaScript

How to find characters in a given string in JavaScript?

In case we need to find characters in a given string using JavaScript, we can follow this approach.

    <input type="text" name="txtName" id="txtName" value="This is a good boy" />
    string to find
    <input type="text" name="txtFind" id="txtFind" value="iss" />
    <input type="button" name="btnTestfunction" value="Find" onclick="TestFunction()" />

        function TestFunction() {
            var string = document.getElementById("txtName").value;
            var toFind = document.getElementById("txtFind").value;
            var find = new RegExp(toFind);

In the above code snippet, we have two textboxes. The 1st textbox contains string and the 2nd textbox contains characters to find from the string.

Onclick of the button, we are calling “TestFunction()” function. In this function we are retrieving the value of textboxes and then instantiating the RegExp (Inbuilt in JavaScript) object by passing the string to find. Then calling the test method of RegExp object by passing the string from which we need to find characters.


 Views: 4791 | Post Order: 9

Write for us

Hosting Recommendations