Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to get the first index of an occurrence of the specified value in a string in JavaScript?
To get the first index of an occurrence of the specified value in a string, use the JavaScript indexOf() method. This method returns the position of the first occurrence of the specified substring, or -1 if not found.
Syntax
string.indexOf(searchValue, startPosition)
Parameters
searchValue: The substring to search for (required)
startPosition: The index to start searching from (optional, default is 0)
Return Value
Returns the index of the first occurrence of the specified value, or -1 if the value is not found.
Example
You can try to run the following code to get the first index:
<html>
<head>
<title>JavaScript String indexOf() Method</title>
</head>
<body>
<script>
var str = new String( "Learning is fun! Learning is sharing!" );
var index = str.indexOf( "Learning" );
document.write("First index of string Learning :" + index );
</script>
</body>
</html>
First index of string Learning :0
More Examples
<html>
<body>
<script>
var text = "JavaScript is awesome. JavaScript is powerful.";
// Find first occurrence of "JavaScript"
document.write("First 'JavaScript' at index: " + text.indexOf("JavaScript") + "<br>");
// Find first occurrence starting from index 10
document.write("Next 'JavaScript' at index: " + text.indexOf("JavaScript", 10) + "<br>");
// Search for non-existent substring
document.write("'Python' found at index: " + text.indexOf("Python") + "<br>");
// Case-sensitive search
document.write("'javascript' (lowercase) at index: " + text.indexOf("javascript"));
</script>
</body>
</html>
First 'JavaScript' at index: 0 Next 'JavaScript' at index: 23 'Python' found at index: -1 'javascript' (lowercase) at index: -1
Key Points
- The search is case-sensitive
- Returns
-1if the substring is not found - The optional second parameter specifies where to start the search
- Index counting starts from 0
Conclusion
The indexOf() method is the standard way to find the first occurrence of a substring in JavaScript. Remember it's case-sensitive and returns -1 when the value is not found.
Advertisements
