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
Previous articles I have explained Ask
or confirm from user before leaving page using JavaScript And What
are the Magic tables or Logical Tables in SQL server and how to access Magic
Tables? And Explain
CTE (Common Table expression) in sql databse? And Disable
right click on images to prevent images from being copied or stolen.
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: