I have a string that looks like this:
var whereClause = "p_id eq @p_id@ and idr_user_id eq @idr_user_id@";
I have the following regular expression to capture the tokens /(@\w+@)/g
I would like to be able to replace each occurrence with a different value something like
whereClause.replace(/(@\w@)/g, projectID, userID);
Will this work? Any Ideas would be helpful...
You could do something like:
whereClause.replace(/@\w+@/g, function(token) {
switch (token) {
case '@p_id@': return projectID;
case '@idr_user_id@': return userID;
}
return token;
});
You could aim for something like this:
template(string, {key: value, key: value});
It could be implemented in a few lines using the replace
callback:
function template(text, obj) {
var regex = /@(\w+)@/g;
return text.replace(regex, function(_, match) {
return obj[match] || _;
});
}
// Usage:
var str = 'p_id eq @p_id@ and idr_user_id eq @idr_user_id@';
var result = template(str, {p_id: 123, idr_user_id: 'ABC'});
//^ "p_d eq 123 and idr_user_id eq ABC"
If you need different regex or structure, you can create a simple closure around those, like:
function template(regex, fn) {
return function (text, obj) {
return text.replace(regex, function(_, match) {
return fn.call(obj, match);
});
}
};
// Using an array
var myTemplate = template(/%(\d+)/g, function(x) {
return this[--x];
});
var str = 'Hello %1, foo %2';
var result = myTemplate(str, ['world', 'baz']);
//^ "Hello world, foo baz"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With