This website collects cookies to deliver better user experience
How to check if a string is a valid URL slug in JavaScript?
How to check if a string is a valid URL slug in JavaScript?
To check if a string is a valid URL slug, we can use a regex expression to match for strings that are small English alphabets separated by a dash in JavaScript.
TL;DR
// Regular expression to check if string is a valid url slugconst regexExp =/^[a-z0-9]+(?:-[a-z0-9]+)*$/g;// String with valid url slugconst str ="hello-world";regexExp.test(str);// true
This is the regex expression for matching almost all the test cases for a valid URL slug in JavaScript.
// Regular expression to check if string is a valid url slugconst regexExp =/^[a-z0-9]+(?:-[a-z0-9]+)*$/g;
Now let's write a string with valid URL slug like this,
// Regular expression to check if string is a valid url slugconst regexExp =/^[a-z0-9]+(?:-[a-z0-9]+)*$/g;// String with valid url slugconst str ="hello-world";
Now to test the string, we can use the test() method available in the regular expression we defined. It can be done like this,
// Regular expression to check if string is a valid url slugconst regexExp =/^[a-z0-9]+(?:-[a-z0-9]+)*$/g;// String with valid url slugconst str ="hello-world";regexExp.test(str);// true
The test() method will accept a string type as an argument to test for a match.
The method will return boolean true if there is a match using the regular expression and false if not.
If you want this as a utility function which you can reuse, here it is,
/* Check if string is a valid URL slug */functioncheckIfValidURLSlug(str){// Regular expression to check if string is a valid url slugconst regexExp =/^[a-z0-9]+(?:-[a-z0-9]+)*$/g;return regexExp.test(str);}// Use the functioncheckIfValidURLSlug("hello-world");// truecheckIfValidURLSlug("HELLO-world");// false