Skip to content

Instantly share code, notes, and snippets.

@jha-adrs
Created September 14, 2024 11:44
Show Gist options
  • Save jha-adrs/c77a9710ba4b78f1cbd3921cb9233893 to your computer and use it in GitHub Desktop.
Save jha-adrs/c77a9710ba4b78f1cbd3921cb9233893 to your computer and use it in GitHub Desktop.
const parseStringToHTML = (input: string) => {
const elements = [];
let tempStr: any = "";
let isBold = false;
const pushElement = (content: any, type: string) => {
if (content) {
if (type === "p") {
elements.push(<p key={elements.length} className="pt-2">{content}</p>);
} else if (type === "li") {
elements.push(
<div className="flex items-start pl-4 ">
<li key={elements.length} className="">
</li>
{content}
</div>
);
} else if (type === "b") {
elements.push(<b key={elements.length}>{content}</b>);
} else {
elements.push(content);
}
}
};
let currentType = "p";
for (let i = 0; i < input.length; i++) {
if (input[i] === "-" && input[i + 1] === "-") {
if (tempStr) {
if (isBold) {
tempStr = <b key={elements.length}>{tempStr}</b>;
isBold = false;
}
pushElement(tempStr, currentType);
}
tempStr = "";
currentType = "p";
i++;
} else if (input[i] === "/" && input[i + 1] === "/" && input[i + 2] === "/") {
if (tempStr) {
if (isBold) {
tempStr = <b key={elements.length}>{tempStr}</b>;
isBold = false;
}
pushElement(tempStr, currentType);
}
tempStr = "";
currentType = "li";
i += 2;
} else if (input[i] === "*" && input[i + 1] === "*") {
if (isBold) {
pushElement(<b key={elements.length}>{tempStr}</b>, "text");
isBold = false;
} else {
pushElement(tempStr, "text");
isBold = true;
}
tempStr = "";
i++;
} else {
tempStr += input[i];
}
}
if (tempStr) {
if (isBold) {
elements.push(<b key={elements.length}>{tempStr}</b>);
} else {
pushElement(tempStr, currentType);
}
}
return elements;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment