Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I check a string starts with a certain substring and ends with a certain substring using regex match

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!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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));
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading