Skip to content

Commit

Permalink
feat(StringTemplate): 支持截断省略
Browse files Browse the repository at this point in the history
  • Loading branch information
fjc0k committed Sep 11, 2024
1 parent ad237a8 commit cae281c
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 3 deletions.
18 changes: 18 additions & 0 deletions src/utils/StringTemplate.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -120,4 +120,22 @@ describe('StringTemplate', () => {
expect(StringTemplate.render('{{false}}', {}, { onlyCode: true })).toBe('')
expect(StringTemplate.render('{{0}}', {}, { onlyCode: true })).toBe('0')
})

test('支持截断省略', () => {
expect(StringTemplate.render('{x#5}', { x: '0123456789' })).toBe('01...')
expect(StringTemplate.render('{x#0}', { x: '0123456789' })).toBe(
'0123456789',
)
expect(StringTemplate.render('{x#1}', { x: '0123456789' })).toBe('...')
expect(StringTemplate.render('{x#8}', { x: '0123456789' })).toBe('01234...')
expect(
StringTemplate.render(
'{x#8}',
{ x: '0123456789' },
{
code: true,
},
),
).toBe('01234...')
})
})
14 changes: 11 additions & 3 deletions src/utils/StringTemplate.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { toSingleLineString } from './toSingleLineString'

export interface StringTemplateRenderOptions {
/** 是否启用代码渲染,需环境支持 eval */
code?: boolean
Expand All @@ -13,6 +15,7 @@ export class StringTemplate {
* 渲染字符串模板。语法:
*
* - 用 `{key}` 直接替换;
* - 用 `{key#10}` 直接替换,取前10个字符省略;
* - 用 `{key:param1,param2}` 执行函数替换;
* - 用 `{{key==='test'?'hi':'hello'}}` 执行代码替换(内部使用 eval 实现,需开启选项里的 `code` 参数)。
*
Expand Down Expand Up @@ -44,10 +47,15 @@ export class StringTemplate {
)
: enableCode
? template.replace(
new RegExp(`(?<!\\$)\\{${key}\\}`, 'g'),
data[key],
new RegExp(`(?<!\\$)\\{${key}(?:#(\\d+))?\\}`, 'g'),
(_, len) =>
len ? toSingleLineString(String(data[key]), +len) : data[key],
)
: template.replace(
new RegExp(`{${key}(?:#(\\d+))?\\}`, 'g'),
(_, len) =>
len ? toSingleLineString(String(data[key]), +len) : data[key],
)
: template.replaceAll(`{${key}}`, data[key])
}
}
if (enableCode) {
Expand Down

0 comments on commit cae281c

Please sign in to comment.