Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript remove special characters from beginning and end of string

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
like image 637
CharliePrynn Avatar asked Feb 19 '26 16:02

CharliePrynn


2 Answers

^\/ 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(); 
like image 63
Sabuj Hassan Avatar answered Feb 21 '26 06:02

Sabuj Hassan


You can simply do this:

var s="/home/about/";
s.match(/[^\/]+/g).join('-'); // home-about
like image 37
Amit Joki Avatar answered Feb 21 '26 05:02

Amit Joki



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!