javascriptregexstringvariables

Reg Ex Match Failing


Im trying to match the following format: < any number of a-z A-Z characters >

Using "^<\w*>$";

The code is:

var predefinedListRegEx = "^<\w*>$";
var dataFill = "<aaaa>"; 
var predefined_List = dataFill.match(predefinedListRegEx);

if (predefined_List != null) {
        //MATCHES THE CONDITION
    }

Cant seem to get it to work.. Where am i going wrong?

Also once i get the matched string i woud like to subtract whats been the <> out And use it to reference a varible.

var vacba = 0 

e.g

And then to vacba = 10;


Solution

  • Your regex here is a String, not a RegExp. Try:

    var predefinedListRegEx = /^<\w*>$/;
    

    If for some reason you need to use a string that is cast to a regex by match, you'd have to escape your slash:

    var predefinedListRegEx = "^<\\w*>$";
    

    In response to your edit with more requests:

    Use a parenthesized match group:

    var predefinedListRegEx = /^<(\w*)>$/;
    var dataFill = "<aaaa>"; 
    var predefined_List = dataFill.match(predefinedListRegEx);
    

    This will set predefinedListRegEx to an array like: ["<aaaa>", "aaaa"].

    If you want to use the string in predefined_List[1] as a variable name (e.g., to do aaaa = 10), you possibly don't need to use eval. If the variable is global, you can simply use window[predefined_List[1]] because all global variables are properties of the window object. If it's not global (or if you just want to be a tidy JavaScript programmer and not overuse the global namespace), you're best off just using referencing properties on an object that holds your values like variablesNamedInMyRegexes[predefined_List[1]] = 10;.