Anthony
Anthony

Reputation: 1876

javascript regex match not working as expected

I'm trying to do something very simple, but I can't get to work the way I intend. I'm sure it's doing exactly what I'm asking it to do, but I'm failing to understand the syntax.

Part 1:

In the following example, I want to extract the part of the string between geotech and Input.

x = "geotechCITYInput"
x.match(/^geotech(.*)(?:Input|List)$/)

The result:

["geotechCITYInput", "CITY"]

I've been writing regex for many years in perl/python and even javascript, but I've never seen the ?: syntax, which, I think, is what I'm supposed to use here.

Part 2:

The higher level problem I'm trying to solve is more complicated. I have a form with many elements defined as either geotechXXXXInput or geotechXXXXList. I want to create an array of XXXX values, but only if the name ends with Input.

Example form definition:

obj0.name = "geotechCITYInput"
obj1.name = "geotechCITYList"
obj2.name = "geotechSTATEInput"
obj3.name = "geotechSTATEList"

I ultimately want an array like this:

["CITY","STATE"]

I can iterate over the form objects easily with an API call, but I can't figure out how to write the regex to match the ones I want. This is what I have right now, but it doesn't work.

geotechForm.forEachItem(function(name) {
    if(name.match(/Input$/)
        inputFieldNames.push( name.match(/^geotech(.*)Input$/) );
});

Any suggestions would be greatly appreciated.

Upvotes: 0

Views: 401

Answers (1)

wired_in
wired_in

Reputation: 2613

You were missing the Input and List suffix in your regex. This will match if the name starts with geotech and ends with either Input or List and it will return an array with the text in the middle as the second item in the array.

geotechForm.forEachItem(function (name) {
    var match = name.match(/^geotech(.*)(Input|List)$/);

    if (match) {
        inputFieldNames.push(match[1]);
    }
});

Upvotes: 1

Related Questions