I have the next string "/1234/somename" and I would like to extract the "somename" out using regexp.
I can use the next code to do the job, but I would like to know how to do the same with 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 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
.)
Try this:
mystring.match( /\/[^\/]+$/ )
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.