Javascript regex 提取最后一个反斜杠之前的字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16863800/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript regex to extract the string before the last backslash
提问by chromedude
I am dealing with timezone's in Javascript and I need a regex that will extract everything, but the timezone name from it. For example, I have the timezone America/Argentina/Buenos_Aires
. I want to extract the America/Argentina
part with a regex. Currently I have this regex: tz.match(/.*?(?=\/|$)/i)[0]
which extracts everything to the first backslash which works for most timezones (America/Los_Angeles
), but not for all of them. How could I edit that regex so that it gets the string before the last value?
我正在处理 Javascript 中的时区,我需要一个正则表达式来提取所有内容,但从中提取时区名称。例如,我有 timezone America/Argentina/Buenos_Aires
。我想America/Argentina
用正则表达式提取部分。目前我有这个正则表达式:tz.match(/.*?(?=\/|$)/i)[0]
它将所有内容提取到第一个反斜杠,适用于大多数时区(America/Los_Angeles
),但不适用于所有时区。我如何编辑该正则表达式,以便它在最后一个值之前获取字符串?
回答by David says reinstate Monica
I'd personally suggest avoiding regular expressions for something like this, when simple string functions/methods would suffice admirably:
我个人建议避免使用正则表达式,因为简单的字符串函数/方法就足够了:
var stringVariable = 'America/Argentina/Buenos_Aires',
text = stringVariable.substring(0, stringVariable.lastIndexOf('/'));