Related Posts Plugin for WordPress, Blogger...

About

Follow Us

Tuesday, 14 July 2015

Introduction:
Some time we need to find the position of the first occurrence of a specified value in given string. In this article I will explain how to find position of the first occurrence of a specified value using Javascript.

In this article I have used “label” control to show position of the first occurrence of a specified substring. Just find the label control in javascript and itialize it with position value.

Following script is used to get the position of the first occurrence of a specified substring:

<script>
    function myFunction() {
        var str = "Search String for Text";
        var n = str. indexOf ("Text");
        document.getElementById("demo").innerHTML = n;
    }
</script>

HTML Code:


<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>


<script>
    function myFunction() {
        var str = "Search String for Text";
        var n = str. indexOf ("Text");
        document.getElementById("demo").innerHTML = n;
    }
</script>



</head>
<body> 
    <form id="form1" runat="server">
    <fieldset style="width:300px"><legend><strong>Search String For Text Using Jquery</strong></legend>
    <div>
    <br />
    Given String: "Search String for Text"
        <br />
    <br />
        <input id="Button2" type="button" onclick='return myFunction()' value="Get Position Of 'Text'" />
        <br />
      <br />
    Position Of "Text" in string is: <label id="demo"></label> <br />
    </div></fieldset>
    </form>
</body>
</html>

0 comments:

Post a Comment