Alon
Alon

Reputation: 3906

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.

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

Upvotes: 0

Views: 212

Answers (3)

Robert Messerle
Robert Messerle

Reputation: 3032

Try this:

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

Upvotes: 0

ruakh
ruakh

Reputation: 183564

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

Upvotes: 0

Michael Berkowski
Michael Berkowski

Reputation: 270767

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();
}

Upvotes: 3

Related Questions