gatsby-remark-find-replace
Version:
Gatsby remark plugin to find and replace text
40 lines (29 loc) • 1.44 kB
JavaScript
;
var _unistUtilVisit = _interopRequireDefault(require("unist-util-visit"));
var _escapeStringRegexp = _interopRequireDefault(require("escape-string-regexp"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
module.exports = ({
markdownAST
}, {
replacements = {},
prefix = '%'
}) => {
// Attaches prefix to the start of the string.
const attachPrefix = str => (prefix || '') + str; // Removes prefix from the start of the string.
const stripPrefix = str => prefix ? str.replace(RegExp(`^${prefix}`), '') : str; // RegExp to find any replacement keys.
const regexp = RegExp('(' + Object.keys(replacements).map(key => (0, _escapeStringRegexp.default)(attachPrefix(key))).join('|') + ')', 'g');
const replacer = (_match, name) => replacements[stripPrefix(name)]; // Go through all text, html, code, inline code, and links.
(0, _unistUtilVisit.default)(markdownAST, ['text', 'html', 'code', 'inlineCode', 'link'], node => {
if (node.type === 'link') {
// For links, the text value is replaced by text node, so we change the
// URL value.
const processedText = node.url.replace(regexp, replacer);
node.url = processedText;
} else {
// For all other nodes, replace the node value.
const processedText = node.value.replace(regexp, replacer);
node.value = processedText;
}
});
return markdownAST;
};