You are here: Home » Tutorials » Web Development » JavaScript » Javascript tutorial - How to find position of a character in a string..

Javascript tutorial - How to find position of a character in a string

Added February 28, 2008, read 2121 times

Find position of a character in a string

In Javascript you will often need to find the position of a certain character in a string. You will learn this by reading this easy tutorial.

Consider the following Javascript functions:

JavaScript Code
stringObject.indexOf(searchvalue,fromindex);
stringObject.lastIndexOf(searchvalue,fromindex);
Select all

The indexOf method returns the position of the first occurrence of the specified value searchvalue in the stringObject string. The lastIndexOf() method returns the position of the last occurrence of the searchvalue, but is searching backwards from the specified position.

We will create a demo to understand how this works. The following HTML creates two textboxes, one for the string to search in, and one for the character of string to be searched, and a button that displays in an alert box the position of the searched string.

HTML Code
<html>
<head>
<title>How the javascript indexOf() method works</title>
</head>

<body>

<input type="text" id="string" />
<input type="text" id="char" />
<input type="submit" value="Get position!" onclick="findPos('string','char')" />

</body>
</html>
Select all

Here is the function that returns the position of the character of string specified in the searchString textfield.

JavaScript Code
function findPos(searchIn, searchFor)
{
	var string = document.getElementById(searchIn).value;
	var character = document.getElementById(searchFor).value;
	var pos = string.indexOf(character);
	alert('Position of "'+character+'" in "'+string+'" is: '+pos+'!');
}
Select all

So the function above gets the string and character entered in the text fields above and displays an alert message box with the position of that character in the string.  You can also use lastIndexOf instead of indexOf.

Full code

JavaScript + HTML Code
<html>
<head>
<title>How the javascript indexOf() method works</title>
<script language="javascript" type="text/javascript">
function findPos(searchIn, searchFor)
{
	var string = document.getElementById(searchIn).value;
	var character = document.getElementById(searchFor).value;
	var pos = string.indexOf(character);
	alert('Position of "'+character+'" in "'+string+'" is: '+pos+'!');
}
</script>
</head>

<body>

<input type="text" id="string" />
<input type="text" id="char" />
<input type="submit" value="Get position!" onclick="findPos('string','char')" />

</body>
</html>
Select all

Demonstration

Discuss

  • Your name
  • Your email (we'll keep this to ourselves)
  • What's it about?
  • Security check

Nobody posted any comments regarding this story. Be the first!