JavaScript

Regular expression in javascript

Regular expression in javascript, someone asked me to explain?

The regular expression is an object that describes pattern of characters that is used to match the character combination of strings.

Example:

 

<script type="text/javascript">

    function processString() {

        // Clear the txtResult element

       document.getElementById("txtResult").value = "";

        // Retrieve the user intput fromthe textbox

        var inputString = document.getElementById("txtInput").value;

        // Regular expression should be in2 forward slashes //

        // Letter g at the end of theregular expression performs a global match

        // match() method returns allsubstrings that match the given regular expression

        var result = inputString.match(/\d+/g);

       alert(result);

        if (result != null) {

            // Add the retrieved numbers tothe txtResult element

            for (var i = 0; i <result.length; i++) {

               document.getElementById("txtResult").value += result[i] + "\r\n";

            }

        }

    }

</script>

<h2>Regular expression in javascript</h2>

 <table style="border:1px solid black;">
    <tr>
        <td>Enter inputstring</td>
        <td>
          <input type="text" id="txtInput" style="width:250px" />
        </td>
    </tr>
    <tr>
        <td>click button to extract</td>
        <td>
         <input type="button" value="extract" onclick="processString()" />
        </td>
    </tr>
    <tr>
        <td>Result</td>
        <td>
          <textarea id="txtResult" rows="4" cols="30"></textarea>
        </td>
    </tr>
</table>

If input string contains words and numbers from that we want to extract all numbers.

Input:

$5,500 per square feet

Output:

regular expression in javascript

 

Note: if you want to extract character just change the javascript code as inputString.match(/\w+/g);.

Post your comments / questions