简体   繁体   English

删除 javascript 中两个“/”之间字符的正则表达式是什么

[英]What is the regexp for removing characters between two "/" in javascript

I have the next string "/1234/somename" and I would like to extract the "somename" out using regexp.我有下一个字符串“/1234/somename”,我想使用正则表达式提取“somename”。

I can use the next code to do the job, but I would like to know how to do the same with RegExp.我可以使用下一个代码来完成这项工作,但我想知道如何使用 RegExp 来完成同样的工作。 mystring.substring(mystring.lastIndexOf("/") + 1, mystring.length)

Thanks谢谢

In a regexp, it can be done like:在正则表达式中,它可以像这样完成:

var pattern = /\/([^\/]+)$/
"/1234/somename".match(pattern);
// ["/somename", "somename"]

The pattern matches all characters following a / (except for another / ) up to the end of the string $ .该模式匹配/之后的所有字符(另一个/除外),直到字符串$的末尾。

However, I would probably use .split() instead:但是,我可能会改用.split()

// Split on the / and pop off the last element
// if a / exists in the string...
var s = "/1234/somename"
if (s.indexOf("/") >= 0) {
  var name = s.split("/").pop();
}

This:这个:

mystring.substring(mystring.lastIndexOf("/") + 1, mystring.length)

is equivalent to this:等同于:

mystring.replace(/.*[/]/s, '')

(Note that despite the name "replace", that method won't modify mystring , but rather, it will return a modified copy of mystring .) (请注意,尽管名称为“replace”,但该方法不会修改mystring ,而是返回mystring的修改副本。)

Try this:试试这个:

mystring.match( /\/[^\/]+$/ )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM