javascripthtmlregexmarkdownshowdown

Javascript RegExp: Searching for everything wrapped with a spezific char or string


I am writing a blog and use markdown language for the entered content to render. Now I try to filter everything outside of code-blocks (marked with triple back-ticks) for HTML-Tags and want to replace them.
However, my current RegExp Pattern isn't working properly, and considering, that I am new to RegExp, i can't find my issue, here is the Pattern I use:

/```(.*)```/g

This works just fine, If I want to strip apart every match, but when I want to split the text, according to this pattern, JavaScript is just looking for the triple back-ticks and not the whole Pattern.

EDIT:
Here is my code where I use the pattern to split the text i get from a textfield:

function preformatInput(text){
    let noCode = text.split(/```(.*)```/g);
    let indizes = [];
    let length = [];
    for(let i = 0; i<noCode.length; i++){
        // indizes.push(text.find(i));
        if(i>0)indizes.push(text.indexOf(noCode[i], text.indexOf(noCode[i-1])));
        else indizes.push(text.indexOf(noCode[i]));

        length.push(noCode[i].length);
    }
    for(let i = 0; i<noCode.length; i++){
        noCode[i] = stripHTML(noCode[i]);
    }
    console.log(indizes);
    console.log(length);
}

Solution

  • /```[^```]+```/g does not work, the expression works the same way as /```[^`]+```/g and forbids single/double '`'s.

    Use

    /```[\s\S]*?```/g
    

    EXPLANATION

    --------------------------------------------------------------------------------
      ```                      '```'
    --------------------------------------------------------------------------------
      [\s\S]*?                 any character of: whitespace (\n, \r, \t,
                               \f, and " "), non-whitespace (all but \n,
                               \r, \t, \f, and " ") (0 or more times
                               (matching the least amount possible))
    --------------------------------------------------------------------------------
      ```                      '```'