debian-mirror-gitlab/app/assets/javascripts/locale/sprintf.js

27 lines
1 KiB
JavaScript
Raw Normal View History

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;
if (parameters) {
2018-12-13 13:39:08 +05:30
Object.keys(parameters).forEach(parameterName => {
2018-03-17 18:26:18 +05:30
const parameterValue = parameters[parameterName];
2020-04-08 14:13:33 +05:30
const escapedParameterValue = escapeParameters ? escape(parameterValue) : parameterValue;
2018-03-17 18:26:18 +05:30
output = output.replace(new RegExp(`%{${parameterName}}`, 'g'), escapedParameterValue);
});
}
return output;
};