Home > OS >  How to match text but don't match if the regex is empty?
How to match text but don't match if the regex is empty?

Time:12-27

The following function searches elements by text:

function findElementsByText(selectors, text) {
  if (text === '') return []

  const regex = new RegExp(text)
  const elements = [...document.querySelectorAll(selectors)]

  return elements.filter((element) => {
    return element.textContent.match(regex)
  })
}

const selectors = 'a'
const text = ''
const foundElements = findElementsByText(selectors, text)
console.log(foundElements)
<a></a>
<a>Text</a>

As you can see, I'm returning [] if text is empty. Without that line, the function will match all the a tags.

I wonder if there's a way to tell the regex: match text but don't match if the regex is empty. This way I can remove the if-statement. Or maybe having the if-statement is the best option?

CodePudding user response:

I would do it like that.

if (!text) return
const text;
  • Related