CharliePrynn
CharliePrynn

Reputation: 3080

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

Upvotes: 3

Views: 6792

Answers (3)

Amit Joki
Amit Joki

Reputation: 59282

You can simply do this:

var s="/home/about/";
s.match(/[^\/]+/g).join('-'); // home-about

Upvotes: 7

Sabuj Hassan
Sabuj Hassan

Reputation: 39405

^\/ 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(); 

Upvotes: 8

przemo_li
przemo_li

Reputation: 4053

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.

Upvotes: 0

Related Questions