I want to check that an input string is a valid shareable Google Forms URL. The requirement is that the input string starts with 'https://docs.google.com/forms/' and ends with 'viewform?usp=sf_link'. I would like to use the .match() with a regex function to accomplish this.
My current function is
isFormsUrl(inputString) {
return inputString.startsWith('https://docs.google.com/forms/') && inputString.endsWith('viewform?usp=sf_link');
}
This function works but I’d like to use regex match() instead of the startsWith() and endsWith() functions to stay consistent with my current codebase. I am very unfamiliar with regex. Thanks!
>Solution :
You can do this using the RegExp test method, which returns true if the string matches the regex.
Note that many characters need to be "escaped" in regex using a backstroke "", namely, ^$/\.?+* though that list is not exhaustive.
You can also use the start and end anchors ^ and $ respectively to specify that the string should match at the start and end.
Combined this is the result:
const strings = [
"https://docs.google.com/forms/viewform?usp=sf_link",
"https://docs.google.com/forms/ LITERALLY ANYTHING viewform?usp=sf_link",
"https://docs.google.com/forms/viewform",
"https://docs.notQuiteRight.com/forms/viewform?usp=sf_link$",
];
const regex = /^https:\/\/docs\.google\.com\/forms\/.*viewform\?usp=sf_link$/;
for (let s of strings) {
console.log(s, regex.test(s));
}