简体   繁体   English

RegExp JavaScript:授权斜线

[英]RegExp javascript : authorize slash

I have a RegExp to format an URL in a HTML input. 我有一个RegExp来格式化HTML输入中的URL。 I want to remove all character which are not letters or numbers. 我要删除不是字母或数字的所有字符。

So I write this regexp : 所以我写了这个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. 我对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. 如果要遵循逻辑,则需要“保护”否定字符类中的/符号(此处- /[^az\\/\Ѐ-\ӿ0-9-]+/g这样就不会删除(为时过早),然后将所有-/-替换为/作为最后一步。 Note that you are duplicating .replace(/[-]+/g, "-") step, you can remove the first one. 请注意,您正在复制.replace(/[-]+/g, "-")步骤,可以删除第一个步骤。

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, "/"); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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