You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

angular-filter中ltrim/rtrim如何按指定字符数实现截断?

How to Implement Left/Right Truncation by Fixed Character Count with angular-filter

Hey there! Let's sort out this issue for you.

First, a quick clarification: the ltrim and rtrim filters in angular-filter are designed to remove specific characters (or whitespace by default) from the start/end of a string—not to truncate a fixed number of characters from either side. That's why your current code isn't working as expected.

Luckily, there are two solid solutions to achieve your goal of truncating by character count:

Creating custom filters gives you explicit, reusable control over left/right truncation by length. Here's how to set them up:

// Add these filters to your Angular module
angular.module('yourAppName')
  // Truncates N characters from the left, returns the remaining string
  .filter('trimLeftByLength', function() {
    return function(input, charCount) {
      // Handle edge cases (empty input, invalid count)
      if (!input || typeof input !== 'string' || charCount < 0) return input;
      // Slice from the specified index to the end
      return input.slice(charCount);
    };
  })
  // Truncates N characters from the right, returns the remaining string
  .filter('trimRightByLength', function() {
    return function(input, charCount) {
      if (!input || typeof input !== 'string' || charCount < 0) return input;
      // Slice from start to (length - charCount)
      return input.slice(0, input.length - charCount);
    };
  });

Then use them in your template just like any other filter:

<td>
  {{player.remarks | truncate: 20:'...':true}} 
  <span>{{player.remarks | trimLeftByLength:5}}</span>
</td>

Solution 2: Repurpose the Existing truncate Filter

If you don't want to add custom filters, you can leverage the truncate filter's optional begin parameter to simulate left truncation.

The truncate filter accepts this syntax: truncate:[length]:[suffix]:[preserve]:[begin]. To keep everything starting from the 5th character, set length to a large value (like Infinity) and begin to 5:

<td>
  {{player.remarks | truncate: 20:'...':true}} 
  <span>{{player.remarks | truncate: Infinity : '' : true : 5}}</span>
</td>

For right truncation (keeping the first X characters), you can use Angular's built-in limitTo filter directly:

<span>{{player.remarks | limitTo: (player.remarks.length - 5)}}</span>

Note: This assumes you know the string is long enough to truncate—add a check if needed to avoid negative values.

Either approach will get you the fixed-length truncation you need. The custom filter route is cleaner for readability and reuse, though!

内容的提问来源于stack exchange,提问作者Jojoseph

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 09:38:41