0

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

Lee Tickett
  • 5,847
  • 8
  • 31
  • 55
Alon
  • 3,734
  • 10
  • 45
  • 64
  • check this link [http://stackoverflow.com/questions/4962176/java-extract-part-of-a-string-between-two-special-characters][1] [1]: http://stackoverflow.com/questions/4962176/java-extract-part-of-a-string-between-two-special-characters – Jassi Oberoi Apr 04 '12 at 14:25

3 Answers3

3

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();
}
Michael Berkowski
  • 267,341
  • 46
  • 444
  • 390
0

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.)

ruakh
  • 175,680
  • 26
  • 273
  • 307
0

Try this:

mystring.match( /\/[^\/]+$/ )
Robert Messerle
  • 3,022
  • 14
  • 18