javascriptregexnegate

Match RegEx with Caret Negation (exclude)


I want to filter my array with an exclusion so I did

const exclude = include.filter((d) => {
                let negate1 = '[^'
                let negate2 = ']'
                let negate = negate1.concat(letterexc).concat(negate2)
                let exclRegex = new RegExp(negate,'g')
                console.log(exclRegex) //return --> /[^anyletter]/g
                return d.list.match(exclRegex)
            })

I add [^ and letterexc variable from an input field and ] to make a negation regex, but its not working. not filtering anything.

I read and tried my pattern here https://regexr.com/ and found if my pattern actually works, but not on my own.

Another article from MDN and link says the similar pattern works (with caret after bracket)

screenshot

EDIT: I added a pen link. It's filtering with 2 input field for letter included and excluded. The included filter works fine


Solution

  • I found it

    I change

    d.list.match(exclRegex)
    

    to

    !d.list.match(exclRegex)
    

    while removing the carat ^ from the concat

    complete code excerpt :

    const exclude = include.filter((d) => {
                    let negate1 = '['
                    let negate2 = ']'
                    let negate = negate1.concat(letterexc).concat(negate2)
                    let exclRegex = new RegExp(negate,'g')
                    console.log(exclRegex) //return --> /[^anyletter]/g
                    return !d.list.match(exclRegex)
                })