If at least one word in the document contains at least one of these letters, do stuff

I want to test if at least one word in an entire document (an entire webpage) contains at least one of the letters in an array of letters and if so, do stuff.

Pseudocode:

const hebrewLetters = ["א", "ב", "ג", "ד", "ה", "ו", "ז", "ח", "ט", "י", "כ", "ל", "מ", "נ", "ס", "ע", "פ", "צ", "ק", "ר", "ש", "ת"];
const [...elements] = document.getElementsByTagName("*");
elements.forEach((element) => {
  if (element.textContent.contains(hebrewLetters)) {
      // Do stuff;
  }
});

I basically test if the current webpage contains at least of of these Hebrew letters (the letters of the entire Hebrew alphabet) and if so, I do stuff.

if (element.textContent == split(hebrewLetters) Something like this?

Hi,

Could you not just do this:

const hebrewLetters = ['א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י', 'כ', 'ל', 'מ', 'נ', 'ס', 'ע', 'פ', 'צ', 'ק', 'ר', 'ש', 'ת'];
const bodyContent = document.body.textContent;
console.log(hebrewLetters.some(letter => bodyContent.includes(letter)));

Basically just grab the text content from the body, then use Array.prototype.some() to test whether at least one letter from the array is present in the body.

It’s not totally robust (e.g. picks up hidden content and script tags), but might be enough for your purpose.

2 Likes

Original code also expands beyond the body.

You may also benefit from telling us what you intend to do with ‘do stuff’, because it may be doable in shorter order than scanning every node of the document.

Do stuff should be something like:

window.open("https://google.com/", "_self");

Blocking any website in Hebrew and transferring the user to Google, as a way for native Hebrew speakers to give more time on learning and practicing other languages.

I’m… not sure that Javascript is going to be able to intercept at the right time for this action.
Are you trying to write a Tampermonkey style script, that runs on the user’s PC?
If you’re putting it into your webpage, you might need to tweak the timing so that google translate has a chance to do its thing before you try and check.

Yes, this should be part of a User Script Manager (USM) script.

Thanks, James,
Your code example helped me a lot to create the following code:

const hebrewLetters = ['א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י', 'כ', 'ל', 'מ', 'נ', 'ס', 'ע', 'פ', 'צ', 'ק', 'ר', 'ש', 'ת'];
const bodyContent = document.body.textContent;
if (hebrewLetters.some(letter => bodyContent.includes(letter))) {
    window.open("https://google.com/", "_self");
}

I tried it to block two websites in Hebrew and they were blocked,
I tried it to block two websites in English and they weren’t blocked,
So, now I have a code which does the desired blocking just fine.

Thanks again,

2 Likes

No worries. Glad I could help :slight_smile:

2 Likes

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.