JavaScript indexOf function will return index of specified searched string, it will return the position else it returns -1. See the code snippet:
JavaScript indexOf function Example - 1
<!DOCTYPE html>
<html>
<head>
<title>Welcome to LearnKode - A code learning platform</title>
</head>
<body>
<button onclick="findPosition()">Find the position of string</button>
<p id="sample"></p>
<script>
function findPosition() {
var str = "Hello world, welcome to learnKode.";
var n = str.indexOf("welcome");
document.getElementById("sample").innerHTML = n;
}
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>Welcome to LearnKode - A code learning platform</title>
</head>
<body>
<button onclick="findPosition()">Find the position of character</button>
<p id="sample"></p>
<script>
function findPosition() {
var str = "Hello world, welcome to the India.";
var n = str.indexOf("e");
document.getElementById("sample").innerHTML = n;
}
</script>
</body>
</html>
Example of JavaScript indexOf function with starting index. See the code snippet:
JavaScript indexOf function Example - 3
<!DOCTYPE html>
<html>
<head>
<title>Welcome to LearnKode - A code learning platform</title>
</head>
<body>
<button onclick="findPosition()">Find the position of character</button>
<p id="sample"></p>
<script>
function findPosition() {
var str = "Hello world, welcome to the India.";
var n = str.indexOf("e",5);
document.getElementById("sample").innerHTML = n;
}
</script>
</body>
</html>