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
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
Share
Improve this question
asked Mar 26, 2014 at 14:38
CharliePrynnCharliePrynn
3,0805 gold badges42 silver badges70 bronze badges
3 Answers
Reset to default 8^\/
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
Instead of replace use finding groups.
Where You will look for a group of any characters prefixed and postfixed with any of the special characters (its only / or some more?).
Next concatenate '-' with that new string, and You are done.