Find Position of sub-string in string using Search() method in JavaScript.

Aman Sharma
0
Introduction:
Some time we need to find the position of substring or word in given string. We can find position of substring by using code in asp.net or by using JavaScript.
In this article I will explain how to find potion of substring using Javascript.

Description:
I have used search() method of JavaScript to find the position of the substring. The search() method searches a string for a specified value, and returns the position of the match. The search value can be string or a regular expression. This method returns -1 if no match is found.

In Javascript function I will pass the string then using search function , I will find the position of the substring. In this article I have used “label” control to show Position no of substring. Just find the label control in javascript and itialize it with position value.

Following script is used to get the position of Substring:

<script>
    function myFunction() {
        var str = "Search String for Text";
        var n = str.search("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.search("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 !