Javascript regular expression: remove first and last slash

前端 未结 4 1138
灰色年华
灰色年华 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: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.

提交回复
热议问题