UNPKG

data-pipeline-information-system-sparql

Version:

Sparql function to query/update RDF through SPARQL 1.1

35 lines (29 loc) 1.11 kB
// <https://stackoverflow.com/questions/3446170/escape-string-for-use-in-javascript-regex> function escapeRegExp(str: string) { return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string } type FormatterOptions = { keyPrefix?: string, keySuffix?: string, asRegExp?: boolean } const defaultOptions: FormatterOptions = { keyPrefix : '', keySuffix: '', asRegExp: true } export function format(templatedString: string, dictionary: { [key: string]: string }, options: FormatterOptions = defaultOptions) { let _options = {...defaultOptions, ...options} let formattedString = templatedString; Object.keys(dictionary).forEach((key) => { let regex:RegExp; if (options.asRegExp){ regex = new RegExp(_options.keyPrefix + key + _options.keySuffix, "g") } else { regex = new RegExp(`${escapeRegExp(_options.keyPrefix + key + _options.keySuffix)}`, "g") } formattedString = formattedString.replace(regex, dictionary[key]) }) return formattedString; } export default format;