Documentation / @andrew_l/toolkit / strAssign
Function: strAssign() ​
strAssign<
T
>(str
,obj
,method
):string
Replaces placeholders in the input string with values from the provided object. The placeholders are denoted by syntax, where
key
is a property name in the object. The function optionally allows a custom method to handle how the values are retrieved from the object.
Type Parameters ​
T ​
T
extends object
Parameters ​
str ​
string
The string with placeholders to be replaced. Placeholders are in the form of .
obj ​
T
The object whose properties will be used to replace the placeholders in the string.
method ​
(obj
, key
) => any
An optional custom method to retrieve values from the object. The default method retrieves the values by accessing the object property directly using the key
.
Returns ​
string
The string with placeholders replaced by the corresponding values from the object.
Examples ​
const context = { name: 'Andrew', age: 30 };
console.log(strAssign('Hey {{ name }}! You are {{ age }} years old.', context));
// Output: 'Hey Andrew! You are 30 years old.'
// Using a custom method
const context2 = { firstName: 'Andrew', lastName: 'L.' };
const customMethod = (obj, key) => {
if (key === 'name') {
return obj.firstName + ' ' + obj.lastName;
}
return obj[key];
};
console.log(strAssign('Hello {{ name }}!', context2, customMethod));
// Output: 'Hello Andrew L.!'