wyc
wyc

Reputation: 55293

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

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?

Upvotes: 0

Views: 76

Answers (1)

Mahony Production
Mahony Production

Reputation: 76

I would do it like that.

if (!text) return
const text;

Upvotes: 1

Related Questions