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.
Written by Michał Kowalkowski
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Javascript
Authors
Related Tags
#javascript
Did you know?
JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.
Security insights from Cside
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#