javascript RegEx -获取URL中最后一个斜杠之后的所有字符

mwg9r5ms  于 2023-08-02  发布在  Java
关注(0)|答案(8)|浏览(135)

我正在使用一个Google API,它以下面的格式返回ID,我将其保存为字符串。我如何在JavaScript中编写正则表达式来将字符串修剪为URL中最后一个斜杠之后的字符。

  1. var id = 'http://www.google.com/m8/feeds/contacts/myemail%40gmail.com/base/nabb80191e23b7d9'

字符串

thigvfpy

thigvfpy1#

不要写正则表达式!这对于字符串函数来说很简单:

  1. var final = id.substring(id.lastIndexOf('/') + 1);

字符串
如果你知道最后一部分总是16个字符,那就更容易了:

  1. var final = id.substring(id.length - 16);

neekobn8

neekobn82#

一个稍微不同的正则表达式方法:

  1. var afterSlashChars = id.match(/\/([^\/]+)\/?$/)[1];

字符串
分解这个正则表达式:

  1. \/ match a slash
  2. ( start of a captured group within the match
  3. [^\/] match a non-slash character
  4. + match one of more of the non-slash characters
  5. ) end of the captured group
  6. \/? allow one optional / at the end of the string
  7. $ match to the end of the string


然后,[1]检索匹配中的第一个捕获的组
工作片段:

  1. var id = 'http://www.google.com/m8/feeds/contacts/myemail%40gmail.com/base/nabb80191e23b7d9';
  2. var afterSlashChars = id.match(/\/([^\/]+)\/?$/)[1];
  3. // display result
  4. document.write(afterSlashChars);

展开查看全部
bn31dyow

bn31dyow3#

以防其他人遇到这个线程并正在寻找一个简单的JS解决方案:
id.split('/').pop(-1)

i5desfxk

i5desfxk4#

这很容易理解(?!.*/).+
让我解释一下:
首先,让我们匹配所有在末尾有斜线的东西,好吗?那是我们不想要的部分
.*/匹配最后一个斜杠之前的所有内容
然后,我们做一个“负向前看”(?!)来表示“我不想要这个,丢弃它”
(?!.*)这是“负前瞻”
现在我们可以很高兴地用这个.+来处理我们不想要的东西旁边的任何东西

您可能需要逃离/因此:

(?!.*\/).+

yqlxgs2m

yqlxgs2m5#

此regexp:[^\/]+$-像冠军一样工作:

  1. var id = ".../base/nabb80191e23b7d9"
  2. result = id.match(/[^\/]+$/)[0];
  3. // results -> "nabb80191e23b7d9"

字符串

kx1ctssn

kx1ctssn6#

这应该可以工作:

  1. last = id.match(/\/([^/]*)$/)[1];
  2. //=> nabb80191e23b7d9

字符串

ct3nt3jp

ct3nt3jp7#

不知道JS,用别人的例子(和猜测)-
id = id.match(/[^\/]*$/);// [0]可选?

1zmg4dgp

1zmg4dgp8#

为什么不用replace?

  1. "http://google.com/aaa".replace(/(.*\/)*/,"")

字符串
收益率“aaa”

相关问题