diff options
| author | ST-DDT <[email protected]> | 2022-03-28 19:28:50 +0200 |
|---|---|---|
| committer | GitHub <[email protected]> | 2022-03-28 17:28:50 +0000 |
| commit | 8d1aefbda070265909cedb07af564ea143be74a7 (patch) | |
| tree | 62fc9556a59d01ac14ecc05debd8d068845b701e /src | |
| parent | d2fc1e6b5ba55242d16b9b8a1e9f42c7b24957b0 (diff) | |
| download | faker-8d1aefbda070265909cedb07af564ea143be74a7.tar.xz faker-8d1aefbda070265909cedb07af564ea143be74a7.zip | |
fix: fake behavior with special replacement patterns (#688)
Diffstat (limited to 'src')
| -rw-r--r-- | src/fake.ts | 22 |
1 files changed, 8 insertions, 14 deletions
diff --git a/src/fake.ts b/src/fake.ts index 854b708a..617708a6 100644 --- a/src/fake.ts +++ b/src/fake.ts @@ -46,32 +46,25 @@ export class Fake { * faker.fake('I flipped the coin an got: {{random.arrayElement(["heads", "tails"])}}') // 'I flipped the coin an got: tails' */ fake(str: string): string { - // setup default response as empty string - let res = ''; - // if incoming str parameter is not provided, return error message if (typeof str !== 'string' || str.length === 0) { throw new Error('string parameter is required!'); } // find first matching {{ and }} - const start = str.search('{{'); - const end = str.search('}}'); + const start = str.search(/{{[a-z]/); + const end = str.indexOf('}}', start); // if no {{ and }} is found, we are done if (start === -1 || end === -1) { return str; } - // console.log('attempting to parse', str); - // extract method name from between the {{ }} that we found // for example: {{name.firstName}} - const token = str.substring(start + 2, end); + const token = str.substring(start + 2, end + 2); let method = token.replace('}}', '').replace('{{', ''); - // console.log('method', method) - // extract method parameters const regExp = /\(([^)]+)\)/; const matches = regExp.exec(method); @@ -111,13 +104,14 @@ export class Fake { let result: string; if (typeof params === 'string' && params.length === 0) { - result = fn(); + result = String(fn()); } else { - result = fn(params); + result = String(fn(params)); } - // replace the found tag with the returned fake value - res = str.replace('{{' + token + '}}', result); + // Replace the found tag with the returned fake value + // We cannot use string.replace here because the result might contain evaluated characters + const res = str.substring(0, start) + result + str.substring(end + 2); if (res === '') { return ''; |
