Home > OS >  RegEx - Excluding pattern from string
RegEx - Excluding pattern from string

Time:11-26

Given this string: (Don't mind the double quotes)

<img alt=""Thanks StackOverflow users <3"" class=""xxx"" src=""xxx"" width=""xxx"" />

I need to select anything except the inner text of the alt attribute.

I came up with this solution but essentialy i need to do the exact opposite but i can't get it to work:

(?<=alt="")(.*?)(?<="")

CodePudding user response:

I think the simplest way might just be to use two capturing groups to get what you want, and another non-capturing group to get what you want to exclude. Here would be an example:

  • enter image description here

    Alternately, you can select what you do want to exclude and replace it, which is the other answer. I'd suggest that approach.

    CodePudding user response:

    You can .replace(/alt=""[^"]""/, 'alt=""""'). It creates a copy without the alt attribute

    const text = '<img alt=""Thanks StackOverflow users <3"" xxx"" src=""xxx"" width=""xxx"" />';
    
    const result = text.replace(/alt=""[^"] ""/, 'alt=""""');
    
    console.log(result);
    <iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related