javascript网址安全的文件名安全的字符串 [英] javascript url-safe filename-safe string
问题描述
正在寻找正则表达式/替换函数,以接受用户输入的字符串,例如"John Smith的Cool Page",并返回文件名/URL安全字符串,例如"john_smith_s_cool_page.html",或类似的内容.
Looking for a regex/replace function to take a user inputted string say, "John Smith's Cool Page" and return a filename/url safe string like "john_smith_s_cool_page.html", or something to that extent.
推荐答案
好吧,这是一个替换不是字母或数字的东西,并将其全部小写的东西,例如您的示例.
Well, here's one that replaces anything that's not a letter or a number, and makes it all lower case, like your example.
var s = "John Smith's Cool Page";
var filename = s.replace(/[^a-z0-9]/gi, '_').toLowerCase();
说明:
正则表达式为/[^a-z0-9]/gi
.好吧,实际上,gi
只是在使用表达式时使用的一组选项.
The regular expression is /[^a-z0-9]/gi
. Well, actually the gi
at the end is just a set of options that are used when the expression is used.
-
i
的意思是忽略大小写差异" -
g
的意思是全局",这实际上意味着应该替换每个匹配,而不仅仅是第一个匹配.
i
means "ignore upper/lower case differences"g
means "global", which really means that every match should be replaced, not just the first one.
所以我们正在寻找的实际上只是[^a-z0-9]
.让我们逐步阅读它:
So what we're looking as is really just [^a-z0-9]
. Let's read it step-by-step:
-
[
和]
定义一个字符类",它是一个单字符列表.如果您要写[one]
,那么它将与'o'或'n'或'e'相匹配. - 但是,字符列表的开头有一个
^
.这意味着它应该只与列表中的不字符匹配. - 最后,字符列表为
a-z0-9
.将此读为"a到z和0到9".这是写abcdefghijklmnopqrstuvwxyz0123456789
的一种简短方法.
- The
[
and]
define a "character class", which is a list of single-characters. If you'd write[one]
, then that would match either 'o' or 'n' or 'e'. - However, there's a
^
at the start of the list of characters. That means it should match only characters not in the list. - Finally, the list of characters is
a-z0-9
. Read this as "a through z and 0 through 9". It's is a short way of writingabcdefghijklmnopqrstuvwxyz0123456789
.
所以基本上,正则表达式是:查找不在'a'和'z'之间或在'0'和'9'之间的每个字母".
So basically, what the regular expression says is: "Find every letter that is not between 'a' and 'z' or between '0' and '9'".
这篇关于javascript网址安全的文件名安全的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!