jk5f3q
Last Updated: February 25, 2016
·
436
· michalkow

Make string url ready

Here is a simple way to convert text so it can be used as a part of url.

var myText = " This Is Some/Text with   tab\nnew line and lot of       spaces\n";
// This Is Some/Text with   tab
//new line and lot of       spaces
//

We will transform our text to lowercase

var myUrl = myText.toLowerCase();
// this is some/text with   tab
//new line and lot of       spaces 
//

Remove spaces, new line characters from begining and end

myUrl = myUrl.replace(/^\s+|\s+$/g,"");
//this is some/text with    tab
//new line and lot of       spaces

Replace tabs, spaces and backslashes with dashes.

myUrl = myUrl.replace(/[\s]+|\t|\n|\r|\//g, "-");
//this-is-some-text-with-tab-new-line-and-lot-of-spaces

Now do everything in one line

myUrl=myText.toLowerCase().replace(/^\s+|\s+$/g,"").replace(/[\s]+|\t|\n|\r/g, "-");

Here is the same thing for php.