Javascript regular expression: remove first and last slash

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

    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)
    

提交回复
热议问题