quatalog-site/js/search_helper.js

41 lines
1.6 KiB
JavaScript
Raw Normal View History

2023-02-11 02:10:08 +00:00
"use strict";
const search_helper = function(event) {
event.preventDefault();
// "a b cde 12" => "a b cde 12"
const input = document.getElementById("search").value.split(" ").join(" ");
2023-02-10 20:50:06 +00:00
console.log(input);
2023-02-11 02:10:08 +00:00
var course_code = false;
if(input.length == 8) {
// "abcd1345" => ["abcd","1345"]
2023-02-11 02:35:21 +00:00
course_code = input.match(/.{1,4}/g)
2023-02-11 02:10:08 +00:00
} else if(input.length == 9) {
// "abcd - 1345" => ["abcd","1345"]
course_code = input.split(/(?:,| )+/);
}
// only do this logic if the string might be a course code
if(course_code) {
// ["abcd","1345"] => "ABCD-1345"
course_code[0] = course_code[0].toUpperCase();
const code_str = course_code.join("-");
// check if "ABCD-1345" is a real course code
const course_exists = fetch("../courses_list.json")
.then(list => list.json())
.then(list => code_str in list);
// if it is, redirect to it
if(course_exists) {
2023-02-11 02:35:21 +00:00
// handle both homepage and courses pages
2023-02-11 06:37:55 +00:00
if(window.location.pathname.split("/").slice(-2,-1)[0] != "courses") {
2023-02-11 02:35:21 +00:00
location.href = "courses/"+code_str;
} else {
location.href = code_str;
}
2023-02-11 02:10:08 +00:00
return;
}
}
location.href = "../search?search=" + encodeURIComponent(input);
2023-02-10 20:50:06 +00:00
}