正则表达式在URL中的斜杠后得到第一个单词 [英] Regex to get first word after slash in URL

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

问题描述

我需要在javascript中的网址中删除斜杠之后的第一个单词,我假设使用正则表达式是理想的。

I need to get the first word after slash in a url in javascript, I assume using a regex would be ideal.

这里有一个关于URL的概念可能看起来像:

Here's an idea of what the URLs can possibly look like :

  • http://mysite.com/section/
  • http://mysite.com/section/subsection/
  • http://mysite.com/section-with-dashes/
  • http://mysite.com/section_with_underscores/

粗体是我需要正则表达式来匹配每个场景,所以基本上只有在斜线之后的第一部分,无论有多少进一步斜线。

In bold is what I need the regex to match for each scenario, so basically only the first portion after the slash, no matter how many further slashes there are.

我在这里完全亏损,感谢帮助。

I'm at a complete loss here, appreciate the help.

推荐答案

使用RegEx的JavaScript。这将匹配第一个之后的任何内容/直到我们遇到另一个/.

JavaScript with RegEx. This will match anything after the first / until we encounter another /.

window.location.pathname.replace(/^\/([^\/]*).*$/, '$1');

这篇关于正则表达式在URL中的斜杠后得到第一个单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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