从标题创建Slugs? [英] Creating Slugs from Titles?

查看:114
本文介绍了从标题创建Slugs?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经掌握了从头衔创造slu g的一切,但有一个问题。我的RegEx用连字符替换空格。但是当用户输入Hi   (多个空格)时,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?

推荐答案

我用这个:

yourslug.replace(/\W+/g, '-')

用一个破折号替换所有出现的一个或多个非字母数字字符。

This replaces all occurrences of one or more non-alphanumeric characters with a single dash.

这篇关于从标题创建Slugs?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆