views:

30

answers:

2

I've got a sinatra app where I plan to make a friedly-urls on the fly. I've got a function with a regexp that looks like this, but it won't turn 'spaces' into 'dashes', ' ' to '-'.

def self.make_slug(title)
  title.downcase.gsub(/ /, '-').gsub(/[^a-z0-9_]/, '').squeeze('-')
end

Thanks in advance!

Update

Now I'm also trying to change åä into a and ö into o, my code looks like this but won't work, any ideas?

gsub(/[åä]/, 'a')
gsub(/[ö]/, 'o')
+1  A: 

Whatever the language, you're first replacing " " with "-", and then replace everything but a-z0-9_ (thus, also "-") with "". Include "-" in the list like [^a-z0-9_-]

mvds
Thanks it worked!
Alfred Nerstu
Any idea how to make åäö into aao?
Alfred Nerstu
Yes, iconv is the magic word and google is your friend. Try `require 'iconv'` and `Iconv.conv("ASCII//TRANSLIT","UTF-8","åäö")`. This does work in irb but (apparently) fails in scripts when there is no locale set. see http://stackoverflow.com/questions/3046462
mvds
+1  A: 
Jason Noble
Good explanation!
Alfred Nerstu