Created
September 1, 2008 03:51
-
-
Save spohlenz/8264 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function slugify(str) { | |
return str.toLowerCase(). | |
replace(/&/g, 'and'). | |
replace(/[^a-z0-9']+/g, '-'). | |
replace(/^-|-$/g, ''); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class String | |
def slugify | |
downcase.gsub(/&/, ' and ').gsub(/[^a-z0-9']+/, '-').gsub(/^-|-$|'/, '') | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') | |
describe "String#slugify" do | |
it "should slugify basic strings" do | |
''.slugify.should == '' | |
'Hello'.slugify.should == 'hello' | |
'ABC 123'.slugify.should == 'abc-123' | |
'Save the chearleader'.slugify.should == 'save-the-chearleader' | |
end | |
it "should slugify strings with punctuation" do | |
'Exclamation mark!'.slugify.should == 'exclamation-mark' | |
'A comma, in a sentence'.slugify.should == 'a-comma-in-a-sentence' | |
'The "end of the world"'.slugify.should == 'the-end-of-the-world' | |
"Sam's page".slugify.should == 'sams-page' | |
end | |
it "should slugify hyphenated and underscored strings and strings with slashes" do | |
'magic-missile'.slugify.should == 'magic-missile' | |
'an_underscore'.slugify.should == 'an-underscore' | |
'a/forward/slash'.slugify.should == 'a-forward-slash' | |
'a\backward\slash'.slugify.should == 'a-backward-slash' | |
end | |
it "should remove consecutive hyphens from result" do | |
'Title - subtitle'.slugify.should == 'title-subtitle' | |
'Multiple spaces'.slugify.should == 'multiple-spaces' | |
end | |
it "should remove hyphens at start and end of result" do | |
' hello '.slugify.should == 'hello' | |
end | |
it "should substitute & with and" do | |
'American Dad & Family Guy'.slugify.should == 'american-dad-and-family-guy' | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment