从标题创建 Slug?
我已准备好从标题创建 slugs 的一切,但有一个问题。我的正则表达式用连字符替换空格。但是,当用户输入“Hi there”(多个空格)时,slug 最终会显示为“Hi-----there”。真正的时候应该是“Hi-there”。
我是否应该创建正则表达式,以便它仅在两侧都有字符时替换空格?
或者有更简单的方法来做到这一点吗?
I have everything in place to create slugs from titles, but there is one issue. My RegEx replaces spaces with hyphens. But when a user types "Hi there" (multiple spaces) the slug ends up as "Hi-----there". When really it should be "Hi-there".
Should I create the regular expression so that it only replaces a space when there is a character either side?
Or is there an easier way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
我使用这个:
这将用一个破折号替换所有出现的一个或多个非字母数字字符。
I use this:
This replaces all occurrences of one or more non-alphanumeric characters with a single dash.
只需匹配多个空白字符即可。
Just match multiple whitespace characters.
丹尼尔的回答是正确的。
但是,如果有人正在寻找完整的解决方案,我喜欢这个功能,
http://dense13.com/blog/2009/05/03/converting-string-to-slug-javascript/
感谢“dense13”!
2024 年 6 月编辑:
上面的链接似乎已失效,但可以通过网络档案访问 此处
该页面概述的解决方案是:
Daniel's answer is correct.
However if somebody is looking for complete solution I like this function,
http://dense13.com/blog/2009/05/03/converting-string-to-slug-javascript/
Thanks to "dense13"!
Edit Jun 2024:
The above link seems dead, but can be accessed through the Web Archive here
The solution outlined on that page is:
作为最后一步,将重复的
-
折叠成一个-
可能是最简单的:或者,如果您只想影响空格,请折叠空格(在其他步骤之前) , 明显地)
It might be the easiest to fold repeated
-
s into one-
as the last step:Or if you only want this to affect spaces, fold spaces instead (before the other steps, obviously)
我会将
[\s]+
替换为'-'
,然后 将[^\w-]
替换为<代码>''I would replace
[\s]+
with'-'
and then replace[^\w-]
with''
您可能需要先修剪字符串,以避免前导和尾随连字符。
You may want to trim the string first, to avoid leading and trailing hyphens.
您可以通过使用简单的包
@smflow/seo-slug
轻松地从标题或任何文本生成 slug:Github如何生成
安装包:@smflow/seo-slug
npm install @smflow/seo-slug
生成 slug
You can do it easily by using a simple package
@smflow/seo-slug
to generate slug from Title or any text: GithubHow to generate
install the package: @smflow/seo-slug
npm install @smflow/seo-slug
Generate the slug