Javascript正则表达式:删除第一个和最后一个斜杠 [英] Javascript regular expression: remove first and last slash

查看:102
本文介绍了Javascript正则表达式:删除第一个和最后一个斜杠的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在javascript中有以下字符串:

I have these strings in javascript:

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

,并且我想删除第一个和最后一个斜杠(如果存在).

and I would like to remove the first and last slash if it's exists.

我尝试了 ^ \/(.+)\/?$ ,但这不起作用.

I tried ^\/(.+)\/?$ but it doesn't work.

通过阅读stackoverflow中的一些文章,我发现php具有修剪功能,可以使用他的javascript翻译( http://phpjs.org/functions/trim :566),但我希望使用简单"的正则表达式.

Reading some post in stackoverflow I found that php has trim function and I could use his javascript translation (http://phpjs.org/functions/trim:566) but I would prefer a "simple" regular expression.

推荐答案

return theString.replace(/^\/|\/$/g, '');

替换所有(/.../g )前斜杠( ^ \/)或( | )末尾斜杠( \/$ )和一个空字符串."

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

这篇关于Javascript正则表达式:删除第一个和最后一个斜杠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆