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

1

3 Answers 3

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();
}
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

0

Try this:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.