I need to hyphenate a string in javascript. The string is a url (e.g '/home/about/').
My current regex, is working but the output is not as desired.
If the first/last character of the string is a special character, it should be removed and instead of being changed into a hyphen.
Example:
var string = '/home/about/';
string.replace(/[^a-zA-Z0-9]/g, '-').toLowerCase();
// Returns -home-about- but I need home-about
^\/ means / at begin and \/$ means / at the end. joined them with pipe to handle both removals from the end.
string = string.replace(/^\/|\/$/g, '').toLowerCase();
Then do your regex operation:
string.replace(/[^a-zA-Z0-9]/g, '-').toLowerCase();
You can simply do this:
var s="/home/about/";
s.match(/[^\/]+/g).join('-'); // home-about
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With