Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get all JS variables that begin with a certain string

I'm writing a plugin for a website that I have no control over except my ability to add JS code to it (in fact it's a set of html docs generated by an obsolete wysiwyg html editor).

For my purposes, I need to get all variables that are named in a certain way. The name always begins with zzz and ends with a number, from zzz1 to zzz999999. Right now I'm doing the following:

for (var i=1; i<999999; i++) {
    if (typeof window['zzz'+i] !== 'undefined') { 
       ArrayOfAllFoundVariables.push( window['zzz'+i] )
    }
}

I wonder if there is a more efficient way to detect these variables other than iterating through a million of undefineds.

like image 227
Sergey Snegirev Avatar asked Mar 24 '13 09:03

Sergey Snegirev


People also ask

What does $() mean in JavaScript?

The $() function The dollar function, $(), can be used as shorthand for the getElementById function. To refer to an element in the Document Object Model (DOM) of an HTML page, the usual function identifying an element is: document.

Can JS variables start with?

Naming Conventions for JavaScript VariablesA variable name must start with a letter, underscore ( _ ), or dollar sign ( $ ). A variable name cannot start with a number. A variable name can only contain alpha-numeric characters ( A-z , 0-9 ) and underscores. A variable name cannot contain spaces.

What does '$' do in JavaScript?

The dollar sign ($) and the underscore (_) characters are JavaScript identifiers, which just means that they identify an object in the same way a name would. The objects they identify include things such as variables, functions, properties, events, and objects.

What is .type in JavaScript?

typeof is a JavaScript keyword that will return the type of a variable when you call it. You can use this to validate function parameters or check if variables are defined. There are other uses as well.


1 Answers

You can iterate through all top level variables (properties of window), and then test if their name match some regex pattern. Collect the matching variables as before.

var pattern = /^zzz[0-9]+/;
for (var varName in window) {
    if (pattern.test(varName)) {
        ArrayOfAllFoundVariables.push(window[varName]);
    }
}
like image 161
Mikke Avatar answered Sep 22 '22 07:09

Mikke