Javascript - String search, what can I fix?

The problem is that when I combine two functions that are:

  • Retrieves all website HTML tag identifiers.
  • looking for an array for "Bad Words" (AKA. "Hack", "Hacker", etc.).

Code 1:

var eleng=document.documentElement.getElementsByTagName('*').length -1; var i=0; var id=[]; function allids() { if (i < eleng) { id.push(document.documentElement.getElementsByTagName('*')[i].id); if (id[i] == '' || id[i] == ' ') { i++; allids(); } else { console.log(id[i]); i++; allids(); } } else { console.log("\nDone!"); } } 

Code 2:

 var str="HELLO"; var words=['hello','hack','hacker']; var i=0; function check() { if (str.indexOf(words[i]) > -1 || str.indexOf(words[i].charAt(0).toUpperCase()) > -1 || str.indexOf(words[i].toUpperCase()) > -1) { console.log('Word Found!'); } else { if (i < words.length) { i++; check(); } } } 

Of course, code 2 would be in a new function already tried, but without success :( and it will be edited to the needs of code 1, I just could not worry about re-writing the script to satisfy I like Save As, but let me know if it is inconvenient.

PS I use Javascript VANILLA, so that means there are no fancy things like jQuery!

+6
source share
2 answers

A quick list of scripts for listing all identifiers on a page can be found here: How to list all html identifiers in a document using javascript?

and then we will combine them in one line and check for bad words as follows:

 var allElements = document.getElementsByTagName("*"); var allIds = []; for (var i = 0, n = allElements.length; i < n; ++i) { var el = allElements[i]; if (el.id) { allIds.push(el.id); } } var str = allIds.join("|").toUpperCase(); var words = ['hello', 'hack', 'hacker']; check(); function check() { words.forEach(function (val, id) { if (str.indexOf(val.toUpperCase()) > -1) { console.log('Word Found!'); } }); } 
 <div id="test"></div> <div id="banana"></div> <div id="sdfsdf"> <div id="test"></div> <div id="test"> <div id="test"></div> <div id="teHACKst"></div> </div> <div id="testHA"></div> </div> <div id="CKtest"></div> <div id="test"></div> <div id="test"></div> 

If you have any questions, feel free to ask.

0
source

Use this code to check array index in javscript ...

 var array = ["rose", "violet", "blue"]; array.indexOf("blue"); // Gives 2 
0
source

Source: https://habr.com/ru/post/983099/


All Articles