Search code examples
javascriptregex

regex capturing incorrect


Simply put, I'm trying to replace certain tags with BBcode. What I have at the moment seems to grab the first <b> skips the following closing tag </b> and instead matches with the next one, leaving a closing tag inbetween them and keeping another one open.

I'm not sure how to fix the expression to capture the two groups of tags separately.

const test = `
 <zxlarge><b>Title and stuff
  - Yo</b></zxlarge>

<zimg>images/path/4137974393811117.png</zimg>



<zlarge><b>Preface.</b></zlarge>

<i>What if making excellent menu systems was as easy as a single command, and you also had access to the code?</i>
`;

let result = test.replace(/<b>([\s\S]*)<\/b>/gi, '[b]$1[/b]');

console.log(result);


Solution

  • By default regexes are greedy, they eat as much as possible as long as they get a match (they will prefer one big match, more than many small matches).

    To make a part of the regex ungreedy, you'll have to replace your * by a *?.

    const test = `
     <zxlarge><b>Title and stuff
      - Yo</b></zxlarge>
    
    <zimg>images/path/4137974393811117.png</zimg>
    
    
    
    <zlarge><b>Preface.</b></zlarge>
    
    <i>What if making excellent menu systems was as easy as a single command, and you also had access to the code?</i>
    `;
    
    let result = test.replace(/<b>([\s\S]*?)<\/b>/gi, '[b]$1[/b]');
    
    console.log(result);