Skip to content
Open
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
15 changes: 12 additions & 3 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,14 @@ module.exports = template

function template(string) {
var args
var opts

if (arguments.length === 2 && typeof arguments[1] === "object") {
args = arguments[1]
} else if (arguments.length === 3 && typeof arguments[1] === "object" &&
typeof arguments[2] === "object") {
args = arguments[1]
opts = arguments[2]
} else {
args = new Array(arguments.length - 1)
for (var i = 1; i < arguments.length; ++i) {
Expand All @@ -25,9 +30,13 @@ function template(string) {
string[index + match.length] === "}") {
return i
} else {
result = args.hasOwnProperty(i) ? args[i] : null
if (result === null || result === undefined) {
return ""
if (opts && opts.rejectNoMatch && !args.hasOwnProperty(i)) {
throw new Error('No matching substitution available for the pattern');
} else {
result = args.hasOwnProperty(i) ? args[i] : null
if (result === null || result === undefined) {
return ""
}
}

return result
Expand Down
18 changes: 18 additions & 0 deletions test/string-template.js
Original file line number Diff line number Diff line change
Expand Up @@ -225,3 +225,21 @@ test("Template string with underscores", function (assert) {
assert.equal(result, "Hello James Bond, how are you?")
assert.end()
})

test("Reject no matching substitution", function (assert) {
assert.throws(function() {
format("I am {name}. I am {age} years old",
{name: "Anna"}, {rejectNoMatch: true})
})
assert.end()
})

test("Allow no matching substitution", function (assert) {
var result
assert.doesNotThrow(function() {
result = format("I am {name}. I am {age} years old",
{name: "Anna"}, {rejectNoMatch: false})
})
assert.equal(result, "I am Anna. I am years old");
assert.end()
})