For my current project, I am attempting to verify if an input field contains a valid "slug." A slug is a string that can only consist of lowercase letters and dashes, typically used in URLs.
An issue I encountered is that a user can enter a valid slug initially, but then follow it with invalid characters. Surprisingly, the regex still returns a match in this scenario.
The regular expression I'm using looks like this: /[a-z\-]+/
It correctly matches: 'my-slug-is-valid'
However, it incorrectly matches: 'my-SLUG-is not valid'
Even though the invalid characters are present after the valid portion, the regex still returns true
.
var re = /[a-z\-]+/,
str = 'my-SLUG-is not valid';
if (re.test(str) && str !== '') {
console.log('Valid');
}
I am wondering if there is a way to modify the regex to return false when encountering characters outside of the defined character-class?