Vincent Decaux February 2016

RegExp javascript : authorize slash

I have a RegExp to format an URL in a HTML input. I want to remove all character which are not letters or numbers.

So I write this regexp :

return url.toLowerCase()
            .replace(/^\s+|\s+$/g, "") 
            .replace(/[_|\s]+/g, "-") 
            .replace(/[^a-z\u0400-\u04FF0-9-]+/g, "") 
            .replace(/[-]+/g, "-") 
            .replace(/^-+|-+$/g, "")
            .replace(/[-]+/g, "-");

But now, I want to accept the slash character ( / ). How can I accept this character through my replaces ? I am not very sure about RegExp.

I want this string :

Category / Test name = dog

To become :

category/test-name-dog

Answers


Wiktor Stribi┼╝ew February 2016

If you want to follow your logic, you need to "protect" the / symbol in the negated character class (here - /[^a-z\/\u0400-\u04FF0-9-]+/g - so that you do not remove it too early), and then replace all -/- with just / as a final step. Note that you are duplicating .replace(/[-]+/g, "-") step, you can remove the first one.

return url.toLowerCase()
            .replace(/^\s+|\s+$/g, "") 
            .replace(/[_\s]+/g, "-") 
            .replace(/[^a-z\/\u0400-\u04FF0-9-]+/g, "") 
            .replace(/^-+|-+$/g, "")
            .replace(/-+/g, "-")
            .replace(/-*\/-*/g, "/");

url = "Category / Test name = dog";
document.body.innerHTML = "Old: " + url.toLowerCase()
            .replace(/^\s+|\s+$/g, "") 
            .replace(/[_|\s]+/g, "-") 
            .replace(/[^a-z\u0400-\u04FF0-9-]+/g, "") 
            .replace(/[-]+/g, "-") 
            .replace(/^-+|-+$/g, "")
            .replace(/[-]+/g, "-");
            // and now
document.body.innerHTML += "<br/>New: " + url.toLowerCase()
            .replace(/^\s+|\s+$/g, "") 
            .replace(/[_\s]+/g, "-") 
            .replace(/[^a-z\/\u0400-\u04FF0-9-]+/g, "") 
            .replace(/^-+|-+$/g, "")
            .replace(/-+/g, "-")
            .replace(/-*\/-*/g, "/");

Post Status

Asked in February 2016
Viewed 2,675 times
Voted 4
Answered 1 times

Search




Leave an answer