GT ClassMethodsFormatting

formatCutoff

GT formatCutoff 方法 API 参考

概览

formatCutoff 方法使用考虑 locale 的结束符号来截断字符串,并根据目标 locale 应用合适的省略号字符和空格。

此方法对于在 UI 中截断文本时遵循各语言标示截断文本的惯例至关重要。

const gt = new GT({
  sourceLocale: 'en',
  targetLocale: 'fr-FR'
});

const formatted = gt.formatCutoff('Hello, world!', {
  maxChars: 8
});
// 返回:"Hello, w\u202F…"(法语中带窄空格)

参考

参数

Prop

Type

Options 对象

PropertyTypeOptionalDescription
localesstring | string[]用于选择结尾符号的 locale(会覆盖实例默认值)
maxCharsnumber最大显示字符数。未定义表示不限。负数表示从末尾起截取
style'ellipsis' | 'none'结尾符号样式。默认为 'ellipsis'
terminatorstring自定义结尾符号,用于覆盖 locale 默认值
separatorstring结尾符号与文本之间的自定义分隔符

CutoffFormatOptions 类型

interface CutoffFormatOptions {
  maxChars?: number;
  style?: 'ellipsis' | 'none';
  terminator?: string;
  separator?: string;
}

返回值

string - 按照 locale 习惯应用适当结束符号后的截断字符串。


行为

Locale 解析

  • 默认使用实例的 _renderingLocales(包含 sourceLocaletargetLocale 和 fallback locale)
  • 可以通过显式的 locales 选项进行覆盖
  • 如果解析失败,则回退到库的默认 locale

字符数限制处理

  • 正值 maxChars:从开头起保留至限制长度,在末尾追加终止符
  • 负值 maxChars:从结尾起保留至限制长度,并在前面添加终止符
  • 零值 maxChars:返回空字符串
  • 未定义的 maxChars:不进行截断,返回原始字符串

基于 locale 的特定行为

该方法会根据语言自动选择合适的结束符号:

  • 法语 (fr):带窄不间断空格(\u202F)的省略号
  • 中文 (zh):不带分隔符的双省略号 ……
  • 日语 (ja):不带分隔符的双省略号 ……
  • 默认:不带分隔符的单省略号

示例

实例 locales 的基本用法

const gt = new GT({ targetLocale: 'en-US' });

const truncated = gt.formatCutoff('Hello, world!', {
  maxChars: 8
});
console.log(truncated); // "Hello, w…"

Locale 覆盖

const gt = new GT({ targetLocale: 'en-US' });

// 覆盖实例的 locale
const french = gt.formatCutoff('Bonjour le monde', {
  locales: 'fr-FR',
  maxChars: 10
});
console.log(french); // "Bonjour\u202F…"

负数字符限制

const gt = new GT({ targetLocale: 'en-US' });

// 从末尾截取
const fromEnd = gt.formatCutoff('JavaScript Framework', {
  maxChars: -9
});
console.log(fromEnd); // "…Framework"

// 更大的负数截取
const moreFromEnd = gt.formatCutoff('Hello, world!', {
  maxChars: -3
});
console.log(moreFromEnd); // "…ld!"

自定义样式选项

const gt = new GT({ targetLocale: 'en-US' });

// 自定义终止符
const custom = gt.formatCutoff('Long description text', {
  maxChars: 12,
  terminator: '...'
});
console.log(custom); // "Long desc..."

// 自定义终止符与分隔符
const customSep = gt.formatCutoff('Another example', {
  maxChars: 10,
  terminator: '[...]',
  separator: ' '
});
console.log(customSep); // "Anot [...]"

// 无终止符
const none = gt.formatCutoff('Clean cut text', {
  maxChars: 5,
  style: 'none'
});
console.log(none); // "Clean"

多语言应用

class UserInterface {
  private gt: GT;
  
  constructor(locale: string) {
    this.gt = new GT({ targetLocale: locale });
  }
  
  truncateTitle(title: string, maxLength = 20): string {
    return this.gt.formatCutoff(title, { maxChars: maxLength });
  }
  
  truncateDescription(description: string): string {
    return this.gt.formatCutoff(description, { maxChars: 100 });
  }
}

const englishUI = new UserInterface('en-US');
const chineseUI = new UserInterface('zh-CN');

console.log(englishUI.truncateTitle('Very Long English Title Here', 15));
// 输出:"Very Long Engl…"

console.log(chineseUI.truncateTitle('很长的中文标题在这里', 8));
// 输出:"很长的中文标题……"

动态 locale 管理

const gt = new GT({ sourceLocale: 'en', targetLocale: 'en' });

function adaptiveText(text: string, userLocale: string, context: 'title' | 'body') {
  const limits = {
    title: { 'en': 50, 'fr': 45, 'de': 40, 'zh': 25 },
    body: { 'en': 200, 'fr': 180, 'de': 160, 'zh': 100 }
  };
  
  const maxChars = limits[context][userLocale] || limits[context]['en'];
  
  return gt.formatCutoff(text, {
    locales: userLocale,
    maxChars
  });
}

// 应用示例
const userPrefs = [
  { locale: 'fr-FR', text: 'Une très longue description française' },
  { locale: 'zh-CN', text: '这是一个非常长的中文描述文本' },
  { locale: 'de-DE', text: 'Eine sehr lange deutsche Beschreibung' }
];

userPrefs.forEach(({ locale, text }) => {
  console.log(`${locale}: ${adaptiveText(text, locale, 'title')}`);
});

注意事项

  • 该方法使用 GT 实例的 _renderingLocales 自动检测 locale
  • 终止符和分隔符的长度会计入字符数上限的计算
  • 如果终止符与分隔符的总长度超过 maxChars,则返回空字符串
  • 自定义终止符会完全覆盖基于 locale 的默认值
  • 通过对 formatter 实例的内部缓存来优化性能

后续步骤

本指南如何?