Skip to content

Commit

Permalink
fix(template): remove regex usage of lookbehind assertions (#1689)
Browse files Browse the repository at this point in the history
* fix(template): remove regex usage of lookbehind assertions

* feat(template): key with space supported
  • Loading branch information
hustcc authored Oct 8, 2020
1 parent baa20f4 commit 92133d0
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 3 deletions.
2 changes: 2 additions & 0 deletions __tests__/unit/utils/template-spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,11 @@ describe('template', () => {
it('template', () => {
const data = { name: 'item1', value: 1, percentage: 0.23 };
expect(template('{name}: {value}', data)).toBe('item1: 1');
expect(template('{ name }: { value }', data)).toBe('item1: 1');
expect(template('{name}\n{value}', data)).toBe('item1\n1');
expect(template('{name {value}', data)).toBe('{name 1');
expect(template('{name} value}', data)).toBe('item1 value}');
expect(template('{name} {name}2 value}', data)).toBe('item1 item12 value}');
expect(template('{name}: {value}({percentage})', data)).toBe('item1: 1(0.23)');
// 没有 match 的 data 原路返回
expect(template('{name}: {value}({percentage1})', data)).toBe('item1: 1({percentage1})');
Expand Down
12 changes: 9 additions & 3 deletions src/utils/template.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,15 @@
import { reduce } from '@antv/util';
/**
* 模板分割符, 默认 { }
* 简单的模板引擎,使用方式如下(空格自动忽略):
* template('hello, {name}', { name: 'AntV' }); // hello, AntV
* @param string
* @param options
*/
export function template(source: string, data: object): string {
// `(?<=y)x` 匹配'x'仅当'x'前面是'y'.这种叫做后行断言; `x(?=y)` 匹配'x'仅仅当'x'后面跟着'y'.这种叫做先行断言。
return source.replace(/{((?<={)[^{}]+(?=}))}/g, (match, key) => data[key.trim()] || match);
return reduce(
// @ts-ignore
data,
(r: string, v: string, k: string) => r.replace(new RegExp(`{\\s*${k}\\s*}`, 'g'), v),
source
);
}

0 comments on commit 92133d0

Please sign in to comment.