What are some methods for implementing string truncation in JavaScript?

  1. The substring() method takes two parameters: the starting position and the ending position, and returns the substring between the starting and ending positions.
let str = "Hello, World!";
let subStr = str.substring(0, 5); // subStr为"Hello"
  1. The slice() method, similar to substring(), accepts a starting and ending position as parameters, and returns the substring between the specified positions. It can also accept negative numbers as parameters, indicating counting positions from the end.
let str = "Hello, World!";
let subStr = str.slice(0, 5); // subStr为"Hello"
  1. The substr() method is used to extract a specified length of characters from a string, starting from a specified position.
let str = "Hello, World!";
let subStr = str.substr(0, 5); // subStr为"Hello"
  1. Utilize a loop in conjunction with the charAt() method to iterate through a string and extract specific characters at a given position.
let str = "Hello, World!"
let subStr = "";
for(let i = 0; i < 5; i++) {
  subStr += str.charAt(i);
}
// subStr为"Hello"

These are commonly used string truncation methods in JavaScript, one should choose the appropriate method based on specific needs.

bannerAds