Substitutor is a easy to use string replacement Javascript library that allows to substitute placeholders of form {name} in string templates with dynamic value's passed at the runtime.
You can replace the placeholders with static values or create values "on-the-fly" by calling a generator. An object is provided as the hashtable to lookup when doing these substitutions. The expression in the curly braces may be a simple property, like id or a dotted expression like data.employee.id.
The string template is written as a regular string with {} expression in the place where a substitution is required. {} expression references a a member of an Object structure or a position in an Array.
The Substitutor library can be used a number of ways.
-substitutes expressions in a string with values from an Array.
var myArray=['404', 'Page Not Found'];
var output = substitutor('Error Code {0} is for {1}', myArray);
Output: Code 404 is for Page Not Found
- substitutes expressions in a string with values from a JSON Object.
var myObj={
"state":"Karnataka",
"capital":"Bangalore"
};
var output = substitutor('The Capital of {state} is {capital}', myObj);
Output: The Capital of Karnataka is Bangalore
var person = {
"first": "Elon",
"last": "Musk",
"title": "Entrepreneur"
};
var template = substitutor("{first} {last} is a great {title}.");
Output: Elon Musk is a great Entrepreneur.
-substitutes expressions in a string with values from an nested objects.
userJson={
"name": {
"first": "John",
"last": "Doe"
},
"phone": {
"work": "1234567",
"home": "4444444"
}
}
var template = substitutor(' {name.first} {name.last} can be
reached at {phone.work} while he’s at work', userJson);
Output: John Doe can be reached at 1234567 while he’s at work.
-replace nested placeholders recursively starting from innermost placeholder.
populationData={
"max":"India",
"min":"Japan",
"India":"1.25 billion",
"USA":"318.9 million",
"Japan":"127.3 million"
}
var output = substitutor('Max Population:{max} ({{max}}) &
Min Population :{min} ({{min}})', populationData);
Output: Max Population:India (1.25 billion) & Min Population :Japan (127.3 million)
-replace a placeholder with a response from function.
var sampleJson={
"time": new Date()
}
var template = substitutor('The time now is {time}',sampleJson);
Output: The time now is Sat Aug 01 2015 12:00:00 GMT+0530
© Copyright 2015 - Substitutor.js