Any idea how i can convert links to this format (text)[link] #247
Unanswered
niveKKumar
asked this question in
Q&A
Replies: 4 comments 2 replies
-
You will need a custom formatter.
|
Beta Was this translation helpful? Give feedback.
1 reply
-
|
Beta Was this translation helpful? Give feedback.
1 reply
-
@niveKKumar did you manage to get it to work? I need this as well |
Beta Was this translation helpful? Give feedback.
0 replies
-
for future ref, this works: import { htmlToText, FormatCallback } from 'html-to-text';
const formatAnchor: FormatCallback = (elem, walk, builder, formatOptions) => {
function getHref() {
if (formatOptions.ignoreHref) {
return '';
}
if (!elem.attribs || !elem.attribs.href) {
return '';
}
const href: string = elem.attribs.href.replace(/^mailto:/, '');
if (formatOptions.noAnchorUrl && href[0] === '#') {
return '';
}
if (formatOptions.baseUrl) {
return formatOptions.baseUrl + href;
}
return href;
}
const href = getHref();
builder.addInline('[');
walk(elem.children, builder);
builder.addInline(']');
const openLinkBracket = formatOptions.linkBrackets ? formatOptions.linkBrackets[0] : '';
const closeLinkBracket = formatOptions.linkBrackets ? formatOptions.linkBrackets[1] : '';
builder.addInline(`${openLinkBracket}${href}${closeLinkBracket}`, {
noWordTransform: true
});
};
const html = `
<div>ABC</div>
<a href="/employment-practices#SAIA" data-hash="#Section-Employmentpractises" class="link-has-image home-page-menu">
<div class="nav-icon">
<img src="/-/media/mom/files/images/home-page/icon-employment-practices.png" alt="Employment practices">
</div>
<span>Employment practices</span>
<span class="nav-desc">
Leave, public holidays, employment rights and conditions, schemes, claims, skills and training.
</span>
</a>
`;
const text = htmlToText(html, {
formatters: {
formatAnchor
},
selectors: [
{ selector: 'img', format: 'skip' },
{ selector: 'svg', format: 'skip' },
{ selector: 'div', format: 'inline' },
{
selector: 'a',
format: 'formatAnchor',
options: { baseUrl: 'https://example.com', linkBrackets: ['(', ')'] }
}
],
wordwrap: false
});
// ABC [ Employment practices Leave, public holidays, employment rights and conditions, schemes, claims, skills and training. ](https://example.com/employment-practices#SAIA)
console.log(text); |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
Hey I would liket to use this lib to convet html strings in discord format, so I am required to convert it not to textblock [link], but my textblock with () around => (textblock)[link]
Beta Was this translation helpful? Give feedback.
All reactions