Get first N characters of a string in Javascript

0
1677
Get first N characters of a string in Javascript
Get first N characters of a string in Javascript

Just another coding tip with Javascript. Let’s learn how to get first N characters of a string in Javascript.

Get first N characters of a string in Javascript

There are two ways to get first N characters of a string in Javascript that are supported in every browser and NodeJS.

  • String method: slice()
  • String method: substring()

String method: slice()

The String.slice(startIndex, endIndex) will return a new string which contains character starting from index startIndex up to, but not including, the index endIndex of the original string. This method does not mutate the original string.

const input = 'Learn some piece of Javascript';

console.log(input.slice(0,5));
// Output: "Learn"

console.log(input.slice(6));
// Output: "some piece of Javascript"

console.log(input.slice());
// Output: "Learn some piece of Javascript"

So, in the words, to get first N characters of a string in Javascript, we will set startIndex = 0, endIndex = N .

String method: substring()

The String.substring(startIndex, endIndex) will return a part of a string from startIndex to endIndex, where character at endIndex is excluded. This method does not mutate the original string.

As said, this method is pretty much identical to the slice() method.

const input = 'Learn some piece of Javascript'; 

console.log(input.substring(0,5)); 
// Output: "Learn" 

console.log(input.substring(6)); 
// Output: "some piece of Javascript" 

console.log(input.substring()); 
// Output: "Learn some piece of Javascript"

Again, to get the first N character of a string in Javascript, we will set startIndex = 0, endIndex = N.

Conclusion

That’s it, very simple and straightforward methods to apply for your Javascript code.

References: