get first n characters javascript

Get the first N characters of the string using Javascript

While doing some projects, we may come across a situation where we need to get only the first 10 characters of the string. This post will help you to achieve that task. Here we are using the different string methods to get the first N characters of a string with javascript.

1. Using String.substring() Method:

// Get the first N characters of the string

// Method 1: Using String.substring()

const string = "www.codeindoor.com";

const getFirstNChars = (str, n) => str.substring(0, n);

const res1 = getFirstNChars(string, 10); //www.codein
const res2 = getFirstNChars(string, 2); //ww
const res3 = getFirstNChars(string, 3); //www

In the above code, we are writing a function that will take a string and a number as a parameter. It will return a string, which is a part of the main string from the first position to the position mentioned in the parameter.

In this, we are using the String.substring() method. This will take 2 parameters, the first parameter is the start position and the second parameter is the end position of the substring which we need.

In String.substring()  method If the first parameter value is greater than the second. The String.substring() method will itself swap the parameters and it will give the substring.

2. Using String.slice() Method:

// Get the first N characters of the string

// Method 2: Using String.slice()

const string = "www.codeindoor.com";

const getFirstNChars = (str, n) => str.slice(0, n);

const res1 = getFirstNChars(string, 10); //www.codein
const res2 = getFirstNChars(string, 2); //ww
const res3 = getFirstNChars(string, 3); //www

Here String.slice() method is used for getting the first N characters of a string. It also takes the start and end positions of the string as parameters and returns a part of a string. In this, we are taking the example where we will get the first 10 characters of a string.

Both String.substring() and String.slice() methods will not change the value of the original string.

Leave a Comment

Your email address will not be published. Required fields are marked *