Ruby post title to slug

后端 未结 5 1162
轮回少年
轮回少年 2020-12-23 19:21

How should I convert a post title to a slug in Ruby?

The title can have any characters, but I only want the slug to allow [a-z0-9-_] (Should it allow an

5条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-23 20:21

    slug = title.downcase.strip.gsub(' ', '-').gsub(/[^\w-]/, '')
    

    downcase makes it lowercase. The strip makes sure there is no leading or trailing whitespace. The first gsub replaces spaces with hyphens. The second gsub removes all non-alpha non-dash non-underscore characters (note that this set is very close to \W but includes the dash as well, which is why it's spelled out here).

提交回复
热议问题