This manual will explain the procedure on how to cut a string to a specific length.
How to Trim a String to a Particular Length in JavaScript?
For trimming a string to a specific length, JavaScript provides some methods given below:
- slice() method
- substring() method
Let’s look at how these methods work.
Method 1: Trim a String to a Particular Length Using slice() Method
To cut the string according to the given length, you can utilize the “slice()” method. It gives only the part of the string as an output until the given limit. It accepts two parameters, the start index and the end index of the slice of a string, as arguments. The second argument is optional; if you will not mention the end index, it considers it as the last index of the string.
Syntax
Follow the below-given syntax to use the slice() method:
Example
In the following example, first, we will create a variable named “strng” and assign it the following string value:
Now, we will trim the string to the 7th index of the string by passing the start index “0” and the end index “7” that will split the string from start to 7th index as a slice of the string:
As you can see the output gives “Welcome” as a slice of the string that starts from 0 index:
Let’s head towards the second method!
Method 2: Trim a String to a Particular Length Using substring() Method
There is another method in JavaScript called “substring()” used to trim a string to a particular length. It also accepts two parameters, the start and the end index of the substring, and returns a part of the string between the specified indexes.
Syntax
You can use the given syntax to trim a string using the substring() method:
Example
Here, we will use the previously created string that is stored in the variable “strng” and call the “substring()” method by passing the start index as “11” and the end index as “20”:
The given output indicates that the string is successfully trimmed based on the particular length:
We have provided the easiest methods related to trimming a string to a particular length.
Conclusion
To trim a string to a particular length, you can use the JavaScript predefined methods, including the slice() method and substring() method. Both methods act the same; you can select anyone which is most suitable for you. This manual explains the procedure for trimming a string to a specific length with detailed examples.