最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

regex - Javascript remove special characters from beginning and end of string - Stack Overflow

programmeradmin3浏览0评论

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
Add a ment  | 

3 Answers 3

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.

发布评论

评论列表(0)

  1. 暂无评论