|
| 1 | +const _htmlTagRegex = /<.*?>/g; |
| 2 | +const _italicRegex = /[_*](.*?)[_*]/g; |
| 3 | +const _boldRegex = /[_*]{2}(.*?)[_*]{2}/g; |
| 4 | + |
| 5 | +/** |
| 6 | + * |
| 7 | + * @param {string} str String to be checked for html tags |
| 8 | + * @returns {string} String with html tags stripped out |
| 9 | + */ |
| 10 | +const _removeHtmlTags = str => str.replace(_htmlTagRegex, ''); |
| 11 | + |
| 12 | +/** |
| 13 | + * Utiltity function for converting markdown into html |
| 14 | + * |
| 15 | + * @param {string} str String to convert to html |
| 16 | + * @param {object} options Object with options for the conversion |
| 17 | + * @param {boolean} options.italic Defines if should convert italic |
| 18 | + * @param {boolean} options.bold Defines if should convert bold |
| 19 | + * @returns {string} String converted to html |
| 20 | + * @example |
| 21 | + * import { markdownConverter } from '@carbon/ibmdotcom-utilities'; |
| 22 | + * |
| 23 | + * markdownConverter('Lorem _ipsum_ __dolor__ *sit* **amet**.') |
| 24 | + */ |
| 25 | +function markdownConverter(str, { italic, bold } = {}) { |
| 26 | + const isAllStyles = !italic && !bold; |
| 27 | + let converted = _removeHtmlTags(str); |
| 28 | + |
| 29 | + if (italic || isAllStyles) { |
| 30 | + converted = converted.replace(_italicRegex, (match, p1) => { |
| 31 | + if (!p1.length) { |
| 32 | + return match; |
| 33 | + } |
| 34 | + return `<em>${p1}</em>`; |
| 35 | + }); |
| 36 | + } |
| 37 | + if (bold || isAllStyles) { |
| 38 | + converted = converted.replace(_boldRegex, '<strong>$1</strong>'); |
| 39 | + } |
| 40 | + |
| 41 | + return converted; |
| 42 | +} |
| 43 | + |
| 44 | +export default markdownConverter; |
0 commit comments