tdc
tdc

Reputation: 5464

What exactly is this jQuery / Regex snippet doing?

I'm not very good with RegEx, and am trying to learn. I have inherited a project which contains the following line of code:

function findCourseIdFromForm(where) {
    var matchRegex = /\[course-[0-9]*\]/;
    var replaceRegex = /\[|\]|[a-z]|\-/g;
    return $(".cnumber", where.parent()).attr("name").match( matchRegex )[0].replace( replaceRegex,"" );
}

I'm not entirely sure what this piece of code is trying to do, but I know that it is causing issues on my page. I'm using jQuery validator and this specific component (".cnumber") is causing the validation to fail and I'm not entirely sure why, so some insight into this line is appreciated.

The .cnumber field in the HTML looks like this:

<input type="hidden" name="courses[course-0][cnumber]" class="cnumber" />

Upvotes: 0

Views: 57

Answers (3)

Oleg
Oleg

Reputation: 23277

This function takes where node, gets its parent, finds .cnumber node within the parent, then takes [course-0] part and finally remove all [, ], -, and lowercase letters.

So the function returns the number that stands after [course- part, or empty string if there is no number

Upvotes: 1

Karl-Andr&#233; Gagnon
Karl-Andr&#233; Gagnon

Reputation: 33870

It just get the course number. In you example, it return 0

Upvotes: 1

jameslafferty
jameslafferty

Reputation: 2182

It strips out [, ], lowercase letters and - from the name attribute in the tag, presumably to return the course number.

Upvotes: 1

Related Questions