2020-04-08 14:13:33 +05:30
|
|
|
import { escape } from 'lodash';
|
2018-03-17 18:26:18 +05:30
|
|
|
|
|
|
|
/**
|
|
|
|
Very limited implementation of sprintf supporting only named parameters.
|
|
|
|
|
|
|
|
@param input (translated) text with parameters (e.g. '%{num_users} users use us')
|
2019-03-02 22:35:43 +05:30
|
|
|
@param {Object} parameters object mapping parameter names to values (e.g. { num_users: 5 })
|
2020-05-24 23:13:21 +05:30
|
|
|
@param {Boolean} escapeParameters whether parameter values should be escaped (see https://lodash.com/docs/4.17.15#escape)
|
2018-03-17 18:26:18 +05:30
|
|
|
@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-12-04 20:38:33 +05:30
|
|
|
@see https://gitlab.com/gitlab-org/gitlab-foss/issues/37992
|
2018-11-08 19:23:39 +05:30
|
|
|
*/
|
2018-03-17 18:26:18 +05:30
|
|
|
export default (input, parameters, escapeParameters = true) => {
|
|
|
|
let output = input;
|
|
|
|
|
2022-10-11 01:57:18 +05:30
|
|
|
output = output.replace(/%+/g, '%');
|
|
|
|
|
2018-03-17 18:26:18 +05:30
|
|
|
if (parameters) {
|
2021-09-04 01:27:46 +05:30
|
|
|
const mappedParameters = new Map(Object.entries(parameters));
|
|
|
|
|
|
|
|
mappedParameters.forEach((key, parameterName) => {
|
|
|
|
const parameterValue = mappedParameters.get(parameterName);
|
2020-04-08 14:13:33 +05:30
|
|
|
const escapedParameterValue = escapeParameters ? escape(parameterValue) : parameterValue;
|
2023-05-27 22:25:52 +05:30
|
|
|
// Pass the param value as a function to ignore special replacement patterns like $` and $'.
|
|
|
|
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#syntax
|
|
|
|
output = output.replace(new RegExp(`%{${parameterName}}`, 'g'), () => escapedParameterValue);
|
2018-03-17 18:26:18 +05:30
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
return output;
|
|
|
|
};
|