Get First n Characters of String in Javascript

Hello coder, In this article, we learn how to get the first n characters of a string in JavaScript. We use .substring() a method that returns the part of a string between the 0 and n indexes.

Example 1

JavaScript

var text = 'Hello, how are you?';

var n = 5;
var substring = text.substring(0,n);

console.log("text: " + text);           // 12345
console.log("substring: " + substring); // 123

Console Result

text: Hello, how are you?
index.html:23 substring: Hello

Example 2

javascript

<script>
   var text = 'abcdefghij';

    var n = 5;
    var substring = text.substring(0,n);

    console.log("text: " + text);           // 12345
    console.log("substring: " + substring); // 123
  </script>

Console Result

text: abcdefghij
index.html:23 substring: abcde