Skip to content

Commit

Permalink
Added list-item UL/OL REGEX replacer
Browse files Browse the repository at this point in the history
Removed linebreak workaround
  • Loading branch information
nuxy committed May 4, 2024
1 parent 954d471 commit 1857e66
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 10 deletions.
18 changes: 17 additions & 1 deletion demo/css/demo.css
Original file line number Diff line number Diff line change
Expand Up @@ -62,12 +62,24 @@ form .textmarked {
padding: 0;
}

#output blockquote,
#output h1,
#output h2,
#output h3,
#output h4,
#output h5,
#output ol,
#output ul {
margin-bottom: 20px;
margin-top: 10px;
}

#output blockquote {
background-color: #eee;
color: #555;
border-left: 2px solid #999;
font-style: italic;
margin: 10px 5px;
margin-left: 5px;
padding: 10px;
}

Expand All @@ -79,3 +91,7 @@ form .textmarked {
#output img {
width: 100%;
}

#output li {
margin-left: 30px;
}
37 changes: 28 additions & 9 deletions src/textmarked.js
Original file line number Diff line number Diff line change
Expand Up @@ -487,13 +487,33 @@ function TextMarked(textarea, settings = {}) {
* @return {String}
*/
function convertToMarkup(text = '') {
const lines = text.split(/\n/);

const lines = text.split(/\n/);
const _lines = [];

let isList = false;

for (let i = 0; i < lines.length; i++) {
let line = lines[i];

// List-item REGEX replacer.
const listReplacer = (tagName, value) => {
value = `<li>${value}</li>`;

const isLastItem = /^\s?(?:-|\d\.){1}\s(.*)$/.test(lines[i + 1]);

if (isList === false && isLastItem) {
value = `<${tagName}>${value}`;
isList = true;
}

if (isList === true && !isLastItem) {
value = `${value}</${tagName}>`;
isList = false;
}

return value;
};

_lines.push(
line

Expand All @@ -520,17 +540,16 @@ function TextMarked(textarea, settings = {}) {

// Link
.replace(/\[([^()]+)\]\(([^()]+)\)/g, '<a href="$2">$1</a>')
);

// Remove <BR> following a block element.
const lastLine = _lines[_lines.length - 2];
// Ordered-List
.replace(/^\s?\d+\.\s(.*)$/, (_, v) => listReplacer('ol', v))

if (line === "" && /(h1|blockquote|hr)>$/.test(lastLine)) {
_lines.pop();
}
// Unordered-List
.replace(/^\s?-\s(.*)$/, (_, v) => listReplacer('ul', v))
);
}

return _lines.join('<br />');
return _lines.join('');
}

/**
Expand Down

0 comments on commit 1857e66

Please sign in to comment.