Using regex in Javascript to match special symbols
I am developing a web application for a school. They have terms like course_name
and class_name
. Think of a course as a temp开发者_JS百科late 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
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
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)"]
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)")
精彩评论