1

I am developing a web application for a school. They have terms like course_name and class_name. Think of a course as a template for a class, meaning that a class must inherit most attributes of a course.

Now, the class_name MUST contain the course_name. For example: if course_name is "CSS" then the class_name can be "CSS 101" or "Beginning CSS". Checking for this is easy using regular expressions. I used to use word boundaries \b\b.

However, I recently ran into an issue where the user typed "HTML (Beginner)" as the course_name. \b being a word boundary will no longer work in this case to find a match in the class_name. Can someone please help me on this? My brain is exploding thinking of all the possibilities. The solution should cover most, if not all, scenarios.

-Mark

Mark
  • 2,137
  • 4
  • 27
  • 42
  • Maybe I wasn't clear in my last paragraph. Using word boundaries on "HTML (Beginner)", like so: new RegExp("\\b"+course_name+"\\b") doesn't work because of the parenthesis. If no parenthesis was present, then the regular expression would have been flawless... – Mark Jan 21 '11 at 03:14

3 Answers3

0

First, you'll need to be able to regex-escape the course name. I'm using the code from this question:

course_name.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')

In order to simulate boundaries when the first/last character in course_name might not be word characters, use the following:

RegExp("(?:^|\\W)" + str + "(?:$|\\W)")

At the beginning, we check for either the beginning of the string or a non-word character, and at the end either the end of the string or a non-word character.

Putting these together, we have:

RegExp("(?:^|\\W)" + course_name.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&') + "(?:$|\\W)")
Community
  • 1
  • 1
Aaron Dufour
  • 17,288
  • 1
  • 47
  • 69
0
var courses = "HTML (Beginner)".match(/\w+/g);//gives ["HTML", "Beginner"];
if (courses)//can be null if no word chars found
  for (var i = 0; i < courses.length; i++)
    //look for course[i] in your list of courses
Walf
  • 8,535
  • 2
  • 44
  • 59
  • Like I mentioned above. There are class_names and course_names and class_names MUST ABSOLUTELY contain every single character found in course_names. Doing /\w+/ would only match the words... My question is: How would I match the parenthesis together with the word as well? – Mark Jan 21 '11 at 03:09
0

You can use 'one or more spaces' as a word separator to extract words and then do a compare right ?

var courses = "HTML (Beginner)".match(/[^\s]+/g); //gives ["HTML", "(Beginner)"]

Ravikiran
  • 1,440
  • 11
  • 15