Bullet Point Convertor Script
December 1, 2020•359 words
A function that converts list item from one format to another
Totally useless to anyone other than me, but this is something I use almost daily. When taking notes, I use a plaintext editor, and consistently make bullet points that contain a link in an easy-to-read format. However, sometimes I need to publish this content (as markdown), and therefore links would look a lot neater if they were using hyperlinks.
So something like this: - Google - A search engine: https://google.com
Would then become this: - [Google](https://google.com) - A search engine
Code
/**
* A function that converts bullet points I make in note format
* into hyperlinks in markdown format, for publishing
*/
function convertBullets (body) {
let result = '';
const lines = body.split(/\r?\n/);
lines.forEach((line)=>{
if(!line.startsWith('- ')){ // Not a bullet, nothing to do here
result += line + '\n';
} else if (!line.match('http')) { // No URL found, nothing to do here
result += line + '\n';
} else if (line.length < 1) { // No content found, nothing to do here
result += line + '\n';
} else { // Here begins the conversion
// Extract the URL from the line
const urlRegex = /(https?:\/\/[^ ]*)/;
const url = line.match(urlRegex)[1];
line = line.replace(urlRegex, '');
// Convert Title + URL into MD Hyperlink
const titleRegex = /(- [a-zA-Z0-9-. ]* -)/;
if (line.match(titleRegex)) { // Double check title format is correct
let title = line.match(titleRegex)[1].replace(/(- | -)/g,'').trim();
line = line.replace(titleRegex, `[${title}](${url}) - `);
} else { // Use text as title (for when desc not provided)
line = `[${line.replace(/[^a-zA-Z ]/g, '').trim()}](${url}) - `;
}
// Remove any trailing chars, and append it to the result
line = line.trim().replace(/:$/, '').replace(/-$/, '')
result += `- ${line} \n`;
}
});
return result; // My work here is done
}
Usage Instructions
To use, just pass a paragraph of notes that may contain unformated bullets into the function, like:
convertBullets(sample);
Either use it through the UI below, or to fork/ make changes, you can use the CLI version here, on Repl.it, or the GUI version here, on JS Fiddle