How to trim a String to N characters in JavaScript

How to trim a String to N characters in JavaScript

This guide will help you learn how to trim a String to N characters in JavaScript by using the substring(), substr(), and slice() functions. It’s helpful for you, let’s read it right now.

Trim a string to N characters in JavaScript

The idea to trim a string to N characters in Javascript is that we need to pass the start index and the end index of that string or the length of it to three functions below, and you can learn more about these functions here.

  • substring(start, end)
  • substr(start, length)
  • slice(start, end)

Parameters:

  •  start: the starting position to extract (required).
  • end: the end position (optional).
  • length: the length of the substring to be taken from the starting position (optional).

Using substring() method

The parameters passed to the substring() function must always be greater than 0.

Code sample:

let string = "Welcome to LearnShareIT";
let trimString = string.substring(3, 10);
document.write(trimString);

Output

come to

Using substr() method

Using substr() method is a simple way to trim a string to N characters in JavaScript. Look at the following example to understand more.

Code sample:

let string = "Welcome to LearnShareIT";
let trimString = string.substr(0, 7);
document.write(trimString);

Output

Welcome

If you pass the start parameter as a negative number, it will count from the end up, and the length parameter must always be positive.

Code sample:

let string = "Welcome to LearnShareIT";
let trimString = string.substr(-12, 12);
document.write(trimString);

Output

LearnShareIT

Using slice() method

Code sample:

let string = "Welcome to LearnShareIT";
let trimString = string.slice(8, 16);
document.write(trimString);

Output

to Learn

If the input parameter is a negative number, it will count backwards, meaning it will count from the bottom up, like this code.

Code sample:

let string = "Welcome to LearnShareIT";
let trimString = string.slice(-12, 23);
document.write(trimString);

Output

LearnShareIT

If you pass only the first parameter, the slice() method will automatically interpret the end position as the last position.

let string = "Welcome to LearnShareIT";
let trimString = string.slice(3);
document.write(trimString);

Output

come to LearnShareIT

Summary

Above, I showed you how to trim a string to N characters in JavaScript using the substring(), substr(), and slice() functions. All three functions have similar ways of doing things, but please pay attention to the special cases of the parameters. I hope they are helpful to you. To better understand the lesson’s content, practice rewriting today’s examples. And let’s learn more about JavaScript in the next lessons here. Have a great day!

Maybe you are interested:

Leave a Reply

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