简体   繁体   中英

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

If you want to follow your logic, you need to "protect" the / symbol in the negated character class (here - /[^az\\/\Ѐ-\ӿ0-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(/[^az\Ѐ-\ӿ0-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(/[^az\\/\Ѐ-\ӿ0-9-]+/g, "") .replace(/^-+|-+$/g, "") .replace(/-+/g, "-") .replace(/-*\\/-*/g, "/"); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM