2020-02-20 13:08:51 -05:00
|
|
|
import { escape } from 'lodash';
|
2017-09-26 05:46:59 -04:00
|
|
|
|
|
|
|
/**
|
|
|
|
Very limited implementation of sprintf supporting only named parameters.
|
|
|
|
|
|
|
|
@param input (translated) text with parameters (e.g. '%{num_users} users use us')
|
2019-01-14 16:46:21 -05:00
|
|
|
@param {Object} parameters object mapping parameter names to values (e.g. { num_users: 5 })
|
2020-04-21 11:21:10 -04:00
|
|
|
@param {Boolean} escapeParameters whether parameter values should be escaped (see https://lodash.com/docs/4.17.15#escape)
|
2017-09-26 05:46:59 -04:00
|
|
|
@returns {String} the text with parameters replaces (e.g. '5 users use us')
|
|
|
|
|
|
|
|
@see https://ruby-doc.org/core-2.3.3/Kernel.html#method-i-sprintf
|
2019-09-18 10:02:45 -04:00
|
|
|
@see https://gitlab.com/gitlab-org/gitlab-foss/issues/37992
|
2018-05-28 05:53:00 -04:00
|
|
|
*/
|
2017-09-26 05:46:59 -04:00
|
|
|
export default (input, parameters, escapeParameters = true) => {
|
2017-10-03 15:08:33 -04:00
|
|
|
let output = input;
|
2017-09-26 05:46:59 -04:00
|
|
|
|
2017-10-03 15:08:33 -04:00
|
|
|
if (parameters) {
|
2021-05-24 05:10:31 -04:00
|
|
|
const mappedParameters = new Map(Object.entries(parameters));
|
|
|
|
|
|
|
|
mappedParameters.forEach((key, parameterName) => {
|
|
|
|
const parameterValue = mappedParameters.get(parameterName);
|
2020-02-20 13:08:51 -05:00
|
|
|
const escapedParameterValue = escapeParameters ? escape(parameterValue) : parameterValue;
|
2017-10-03 15:08:33 -04:00
|
|
|
output = output.replace(new RegExp(`%{${parameterName}}`, 'g'), escapedParameterValue);
|
|
|
|
});
|
|
|
|
}
|
2017-09-26 05:46:59 -04:00
|
|
|
|
2017-10-03 15:08:33 -04:00
|
|
|
return output;
|
|
|
|
};
|