Javascript regular expression: remove first and last slash

前端 未结 4 1135
灰色年华
灰色年华 2020-12-12 19:13

I have these strings in javascript:

/banking/bonifici/italia
/banking/bonifici/italia/

and I would like to remove the first and last slash

相关标签:
4条回答
  • 2020-12-12 19:52

    There's no real reason to use a regex here, string functions will work fine:

    var string = "/banking/bonifici/italia/";
    if (string.charAt(0) == "/") string = string.substr(1);
    if (string.charAt(string.length - 1) == "/") string = string.substr(0, string.length - 1);
    // string => "banking/bonifici/italia"
    

    See this in action on jsFiddle.

    References:

    • String.substr
    • String.charAt
    0 讨论(0)
  • 2020-12-12 19:55

    In case if using RegExp is not an option, or you have to handle corner cases while working with URLs (such as double/triple slashes or empty lines without complex replacements), or utilizing additional processing, here's a less obvious, but more functional-style solution:

    const urls = [
      '//some/link///to/the/resource/',
      '/root',
      '/something/else',
    ];
    
    const trimmedUrls = urls.map(url => url.split('/').filter(x => x).join('/'));
    
    console.log(trimmedUrls);

    In this snippet filter() function can implement more complex logic than just filtering empty strings (which is default behavior).

    Word of warning - this is not as fast as other snippets here.

    0 讨论(0)
  • 2020-12-12 19:55

    Just in case that someone needs a premature optimization here...

    http://jsperf.com/remove-leading-and-trailing-slashes/5

    var path = '///foo/is/not/equal/to/bar///'
    var count = path.length - 1
    var index = 0
    
    while (path.charCodeAt(index) === 47 && ++index);
    while (path.charCodeAt(count) === 47 && --count);
    
    path = path.slice(index, count + 1)
    
    0 讨论(0)
  • 2020-12-12 19:59
    return theString.replace(/^\/|\/$/g, '');
    

    "Replace all (/.../g) leading slash (^\/) or (|) trailing slash (\/$) with an empty string."

    0 讨论(0)
提交回复
热议问题