0

I am busy writing a simple HTML to Github markdown function. My idea is to have an array of objects which define a 'mapping' of sorts, from an HTML tag to a markdown symbol with an associated regular expression.

regExpReplace is meant to take a string of HTML to parse and it will run over each item in the lessonToMDMap and replace each HTML tag via the corresponding regular expression with the help of .replace(). I am trying to figure out how I can update the markdown string defined inside of regExpReplace from within the forEach callback function. The code doesn't currently work because the arrow function callback has access to the parent scope (the lexical scope of the forEach function). The function runs but doesn't modify the string for this reason.

My question is if there is a few that I can access the parents scope outside of the forEach from within the arrow function callback? Is there a way to bind the scope to the callback?

    //Define mapping in this array of objects
    const lessonToMDMap = [
    {
            htmlTag: '<span class="ql-size-large">',
            mdTag: "##",
            regExp: RegExp(/\<(span)\s(class)\=("ql-size-large")\>/,'g'),
        },
        {
            htmlTag: '<span class="ql-size-huge">',
            mdTag: "#",
            regExp: RegExp(/\<(span)\s(class)\=("ql-size-huge")\>/,'g')
        },
    ]

    //Function for making replacements of html tags
    const regExpReplace = function (mapArray, stringToParse) {
        let markdown = '' + stringToParse;
        mapArray.forEach((mapItem)=>{
            markdown = markdown.replace(mapItem.regExp,mapItem.mdTag);
        })
        return markdown;
    };

I tried defining the callback as an arrow function within regExpReplace too like below however I am still unable to modify the string.

//Function for making replacements of html tags
    const regExpReplace = function (mapArray, stringToParse) {
        let markdown = '' + stringToParse;
        const replace = (mapItem) => {
            markdown = markdown.replace(mapItem.regExp,mapItem.mdTag);
        }
        mapArray.forEach(replace);
        return markdown;
    };
Blargian
  • 294
  • 3
  • 14
  • 2
    Your code works fine on my side. Also, please stop summoning [Tony the Pony](https://stackoverflow.com/a/1732454/3670132). Regex should not be used to parse HTML. A DOM parser would be much more appropriate and easier to implement. – Seblor Jun 05 '21 at 19:27
  • @Seblor yikes! Tony the Pony noted. I will never do this again. Thanks. – Blargian Jun 06 '21 at 06:33

0 Answers0