Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Rewrite input to friendly URL (See related posts)

// Take an input and rewrite it to a friendly-url-like-this

   1  
   2  <script type="text/javascript">
   3  
   4  	// Store the current title value
   5  	var title = 'This is a title with a symbol &'
   6  
   7  	// alert(title); // debug
   8  
   9  	// Clean up the title		
  10  	var url = title
  11  		.toLowerCase() // change everything to lowercase
  12  		.replace(/^\s+|\s+$/g, "") // trim leading and trailing spaces		
  13  		.replace(/[_|\s]+/g, "-") // change all spaces and underscores to a hyphen
  14  		.replace(/[^a-z0-9-]+/g, "") // remove all non-alphanumeric characters except the hyphen
  15  		.replace(/[-]+/g, "-") // replace multiple instances of the hyphen with a single instance
  16  		.replace(/^-+|-+$/g, "") // trim leading and trailing hyphens				
  17  		; 
  18  	
  19  	alert(url); // outputs 'this-is-a-title-with-a-symbol'
  20  
  21  </script>

You need to create an account or log in to post comments to this site.


Click here to browse all 5521 code snippets

Related Posts