Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(template): remove regex usage of lookbehind assertions #1689

Merged
merged 2 commits into from
Oct 8, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
);
}