Skip to content

Commit

Permalink
Make interpolate escape HTML in variables - Fix #78
Browse files Browse the repository at this point in the history
  • Loading branch information
kemar committed Oct 17, 2018
1 parent f53d817 commit 44e409d
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 0 deletions.
11 changes: 11 additions & 0 deletions src/interpolate.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,14 @@ let interpolate = function (msgid, context = {}) {
const expression = token.trim()
let evaluated

let escapeHtmlMap = {
'&': '&',
'<': '&lt;',
'>': '&gt;',
'"': '&quot;',
'\'': '&#039;',
}

// Avoid eval() by splitting `expression` and looping through its different properties if any, see #55.
function getProps (obj, expression) {
const arr = expression.split(EVALUATION_RE).filter(x => x)
Expand All @@ -69,6 +77,9 @@ let interpolate = function (msgid, context = {}) {
}
}
return evaluated
.toString()
// Escape HTML, see #78.
.replace(/[&<>"']/g, function (m) { return escapeHtmlMap[m] })
}

return evalInContext.call(context, expression)
Expand Down
7 changes: 7 additions & 0 deletions test/specs/interpolate.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,13 @@ describe('Interpolate tests', () => {
expect(interpolated).to.equal('Foo bar baz')
})

it('with HTML in var (should be escaped)', () => {
let msgid = 'Foo %{ placeholder } baz'
let context = { placeholder: '<p>bar</p>' }
let interpolated = interpolate(msgid, context)
expect(interpolated).to.equal('Foo &lt;p&gt;bar&lt;/p&gt; baz')
})

it('with multiple spaces in the placeholder', () => {
let msgid = 'Foo %{ placeholder } baz'
let context = { placeholder: 'bar' }
Expand Down

0 comments on commit 44e409d

Please sign in to comment.