3 Example(s) of JavaScript substr function


Description :

JavaScript Substr function is used to extract characters from string. Two parameters one is start index and 2nd is number of characters. var str = "I Love LearnKode."; var result = str.substr(1, 5); See the code snippet:


JavaScript substr function Example - 1
<!DOCTYPE html>
<html>
<head>
<title>Welcome to LearnKode - A code learning platform</title>
</head>
<body>
    <button onclick="extractSubpart()">Click to extract subpart of string</button>
    <p id ="sample"></p>
  <script>
  function extractSubpart()
  {
     var str = "I Love LearnKode.";
     var result = str.substr(1, 5);
     document.getElementById("sample").innerHTML=result;
  }
  </script>

</body>
</html>

Output

Description :

Javascript Substr function is used to extract the string out of string and it has two parameters where first one is starting point and second one is optional and that defines the length or number of characters that should be extracted out.


JavaScript substr function Example - 2
<!DOCTYPE html>
<html>
<head>
<title>Welcome to LearnKode - A code learning platform</title>
</head>
<body>
    <button onclick="extractSubpart()">Extract subpart of string</button>
    <p id ="sample"></p>
  <script>
  function extractSubpart()
  {
    var str = "I LOVE LEARNKODE";
    var result = str.substr(2);
     document.getElementById("sample").innerHTML=result;
  }
  </script>

</body>
</html>

Output

Description :

JavaScript substring function is used to extract string from string, There are two parameter where first one parameter is start and second one is optional.



JavaScript substr function Example - 3
<!DOCTYPE html>
<html>
<head>
<title>Welcome to LearnKode - A code learning platform</title>
</head>
<body>
   <script>
    var anyString = 'Mozilla';
    var result= anyString.substring(anyString.length - 4);
    document.write(result);
   </script>
</body>
</html>

Output