diff options
author | Winnie Hellmann <winnie@gitlab.com> | 2017-09-26 12:46:59 +0300 |
---|---|---|
committer | Winnie Hellmann <winnie@gitlab.com> | 2017-10-03 15:46:19 +0300 |
commit | b509588a28d0a102f4ad4b97d91c5b5944946834 (patch) | |
tree | 1ace10c95ed2573f14927ddee014c562ab987621 /app/assets/javascripts/locale/sprintf.js | |
parent | 92173ac55cd921a65ce137e238ed8bc4474aaccb (diff) |
Add basic sprintf implementation to JavaScript
Diffstat (limited to 'app/assets/javascripts/locale/sprintf.js')
-rw-r--r-- | app/assets/javascripts/locale/sprintf.js | 26 |
1 files changed, 26 insertions, 0 deletions
diff --git a/app/assets/javascripts/locale/sprintf.js b/app/assets/javascripts/locale/sprintf.js new file mode 100644 index 00000000000..003cbe820d6 --- /dev/null +++ b/app/assets/javascripts/locale/sprintf.js @@ -0,0 +1,26 @@ +import _ from 'underscore'; + +/** + Very limited implementation of sprintf supporting only named parameters. + + @param input (translated) text with parameters (e.g. '%{num_users} users use us') + @param parameters object mapping parameter names to values (e.g. { num_users: 5 }) + @param escapeParameters whether parameter values should be escaped (see http://underscorejs.org/#escape) + @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 + @see https://gitlab.com/gitlab-org/gitlab-ce/issues/37992 +**/ +export default (input, parameters, escapeParameters = true) => { + let output = input; + + if (parameters) { + Object.keys(parameters).forEach((parameterName) => { + const parameterValue = parameters[parameterName]; + const escapedParameterValue = escapeParameters ? _.escape(parameterValue) : parameterValue; + output = output.replace(new RegExp(`%{${parameterName}}`, 'g'), escapedParameterValue); + }); + } + + return output; +} |