let template = ('[[ReadItLater]] [[Article]] %articleContent%')
let content = 'For example, the Regex pattern or quantifier `^(a+)+$` is represented by the following NFA'
console.log(template.replace(/%articleContent%/g, () => content))
Expect:
[[ReadItLater]] [[Article]] For example, the Regex pattern or quantifier `^(a+)+$` is represented by the following NFA
Got:
[[ReadItLater]] [[Article]] For example, the Regex pattern or quantifier ^(a+)+[[ReadItLater]] [[Article]] is represented by the following NFA
Motivation and Context
I wrapped the necessary parts with an anonymous function. Using an anonymous function can bypass this issue because JavaScript directly uses the result of the anonymous function for replacement.
[x] Bug fix (prefix: fix - non-breaking change which fixes an issue)
[ ] New feature (prefix: feat - non-breaking change which adds functionality)
[ ] Breaking change (prefix: feat!! or fix!! - fix or feature that would cause existing functionality to not work as expected)
[ ] Documentation (prefix: docs - improvements to any documentation content)
Internal changes:
[ ] Refactor (prefix: refactor - non-breaking change which only improves the design or structure of existing code, and making no changes to its external behaviour)
[ ] Tests (prefix: test - additions and improvements to unit tests and the smoke tests)
Use anonymous functions to return replacement strings where necessary to avoid issues caused by special replacement patterns in the content
Description
The code heavily uses the pattern of replacing placeholders with specific content to achieve a template-like functionality. However, if the content contains special replacement patterns as mentioned in https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#specifying_a_string_as_the_replacement, there will be issues with incorrect replacements. A minimal reproducible example:
Expect:
Got:
Motivation and Context
I wrapped the necessary parts with an anonymous function. Using an anonymous function can bypass this issue because JavaScript directly uses the result of the anonymous function for replacement.
How has this been tested?
Real world example:
https://owasp.org/www-community/attacks/Regular_expression_Denial_of_Service_-_ReDoS
Before fix:
After fix:
Screenshots (if appropriate)
Types of changes
Changes visible to users:
fix
- non-breaking change which fixes an issue)feat
- non-breaking change which adds functionality)feat!!
orfix!!
- fix or feature that would cause existing functionality to not work as expected)docs
- improvements to any documentation content)Internal changes:
refactor
- non-breaking change which only improves the design or structure of existing code, and making no changes to its external behaviour)test
- additions and improvements to unit tests and the smoke tests)chore
- examples include GitHub Actions, issue templates)Checklist
npm run lint
.