JavaScript: Find position of first occurrence of sub-string or value using IndexOf method in JavaScript.

Aman Sharma
0
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.

Description:
I have used “string.indexOf()” method of JavaScript to find the position of the first occurrence of a specified substring or value. The indexOf() method searches a string for a specified value, and returns the the position of the first occurrence of a specified substring or value. This method return -1 if no match is found.


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>



Demo:

Post a Comment

0Comments
Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !