sorry in advance if this has been asked before, i looked around and couldn't find anything that answered my question or worked for me
on my HTML webpage i have an existing script that imports and prints text from an external source. this source is written in markdown, so it very blockily prints [text](url)
rather than functionally displaying <a href="url">text</a>
my goal is to write a script that manually detects the markdown URL formatting in printed text and converts it to the functional HTML formatting instead, so it no longer prints a long string of text and shows up properly as a hyperlink. this script should run after the external text is imported so it detects properly.
i admit i'm brand new to javascript entirely so i'm not familiar with it at all, i haven't been able to find an existing script anywhere that does what i'm looking for so i've been trying to frankenstein my own but it hasn't been working out for me. patience is appreciated, and if someone would be willing to walk me through how it works i'd appreciate that too!
i found an existing code on github that advertises as doing exactly as i want it to. i wanted to modify it to detect text by class rather than exact text given the imported text is a conditional variable that changes depending on the external source.
what i managed to come up with was this, but again i reiterate i know nothing about javascript and i'm just winging it based off of external examples that do relatively the same thing?
var prNs = document.getElementsByClassName('pk');
let elements = prNs.match(/\[.*?\)/g);
if( elements != null && elements.length > 0){
for(el of elements){
let txt = el.match(/\[(.*?)\]/)[1];//get only the txt
let url = el.match(/\((.*?)\)/)[1];//get only the link
prNs = prNs.replace(el,'<a href="'+url+'" target="_blank">'+txt+'</a>')
}
}
You have multiple issues with your code.
getElementsByClassName
returns array-like object of elements, so you need to loop through if you have multiple elements or if you have just one get it with index 0
/\[([^\]]+)\]\(([^)]+)\)/g
innerHTML
var elements = document.getElementsByClassName('pk');
for (let i = 0; i < elements.length; i++) {
let element = elements[i];
let content = element.innerHTML;
let markdownLinkRegex = /\[([^\]]+)\]\(([^)]+)\)/g;
// Replace all Markdown links with HTML links in the content
let updatedContent = content.replace(markdownLinkRegex, function(match, text, url) {
return '<a href="' + url + '" target="_blank">' + text + '</a>';
});
element.innerHTML = updatedContent;
}