Ghost/ghost/security/lib/string.js
kirrg001 411ce69006 Moved tokens, url safe and safe string utility to lib/security
refs #9178

- we could now also move any crypto usages to lib/security, but no priority
- the main goal is to tidy up our utils folder
2017-12-14 13:38:00 +01:00

41 lines
1.2 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

'use strict';
const unidecode = require('unidecode'),
_ = require('lodash');
module.exports.safe = function safe(string, options) {
options = options || {};
if (string === null) {
string = '';
}
// Handle the £ symbol separately, since it needs to be removed before the unicode conversion.
string = string.replace(/£/g, '-');
// Remove non ascii characters
string = unidecode(string);
// Replace URL reserved chars: `@:/?#[]!$&()*+,;=` as well as `\%<>|^~£"{}` and \`
string = string.replace(/(\s|\.|@|:|\/|\?|#|\[|\]|!|\$|&|\(|\)|\*|\+|,|;|=|\\|%|<|>|\||\^|~|"|\{|\}|`||—)/g, '-')
// Remove apostrophes
.replace(/'/g, '')
// Make the whole thing lowercase
.toLowerCase();
// We do not need to make the following changes when importing data
if (!_.has(options, 'importing') || !options.importing) {
// Convert 2 or more dashes into a single dash
string = string.replace(/-+/g, '-')
// Remove trailing dash
.replace(/-$/, '')
// Remove any dashes at the beginning
.replace(/^-/, '');
}
// Handle whitespace at the beginning or end.
string = string.trim();
return string;
};