2 Example(s) of JavaScript substring function


Description :

JavaScript substring() is used to extract characters from a string. two parameters one is start index and the second is end index. if 2nd parameters is not passed then this method will extract till the end of string. See the code snippet:


JavaScript substring function Example - 1
<!DOCTYPE html>
<html>
<head>
<title>Welcome to LearnKode - A code learning platform</title>
</head>
<body>
   <p>Click the button to extract characters from the string.</p>
<button onclick="extractSubset()">Show the substring</button>
<p id="sample"></p>
<script>
function extractSubset() {
    var str = "i love learnkode";
    var result = str.substring(7, 16);
    document.getElementById("sample").innerHTML = result;
}
</script>
</body>
</html>

Output

Description :

Example of JavaScript substring function without second parameter:


JavaScript substring function Example - 2
<!DOCTYPE html>
<html>
<head>
<title>Welcome to LearnKode - A code learning platform</title>
</head>
<body>
   <p>Click the button to extract characters from the string. <br/>
Original string : i love learnkode
</p>
<button onclick="extractSubset()">Show the substring</button>
<p id="sample"></p>
<script>
function extractSubset() {
    var str = "i love learnkode";
    var result = str.substring(2);
    document.getElementById("sample").innerHTML = result;
}
</script>

</body>
</html>

Output