Showing posts with label Searching substring. Show all posts
Showing posts with label Searching substring. Show all posts

Saturday, February 10, 2024

Write a JavaScript code for searching a substring in a given string and return the position. MCSL-016

 This is a solution for the previous question asked in MCSL-016 LAB of Ignou exams.


Write a JavaScript code for searching a substring in a given string and return the position. 


<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Substring Search</title>

<script>

function findSubstringPosition() {

    var mainString = document.getElementById("mainString").value;

    var substring = document.getElementById("substring").value;

    

    // Use indexOf() to find the position of the substring in the main string

    var position = mainString.indexOf(substring);

    

    // Display the result

    if (position !== -1) {

        document.getElementById("result").innerText = "Substring found at position: " + position;

    } else {

        document.getElementById("result").innerText = "Substring not found.";

    }

}

</script>

</head>

<body>

<h2>Substring Search</h2>

<p>Enter a main string and a substring to find its position:</p>

<input type="text" id="mainString" placeholder="Enter main string">

<input type="text" id="substring" placeholder="Enter substring">

<button onclick="findSubstringPosition()">Search</button>

<p id="result"></p>

</body>

</html>