Skip to content

Commit f7ca1e5

Browse files
feat(markdown-converter): implement markdown converter utility
1 parent 4e4b7e1 commit f7ca1e5

File tree

3 files changed

+53
-0
lines changed

3 files changed

+53
-0
lines changed

packages/utilities/src/utilities/index.js

+1
Original file line numberDiff line numberDiff line change
@@ -11,4 +11,5 @@ export * from './featureflag';
1111
export * from './geolocation';
1212
export * from './ipcinfoCookie';
1313
export * from './serialize';
14+
export * from './markdownconverter';
1415
export * from './settings';
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
/**
2+
* Copyright IBM Corp. 2016, 2018
3+
*
4+
* This source code is licensed under the Apache-2.0 license found in the
5+
* LICENSE file in the root directory of this source tree.
6+
*/
7+
8+
export { default as markdownConverter } from './markdownconverter';
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
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

Comments
 (0)