0

Say I have a url like /dir/name.json and I want to select and return anything which is between /dir/ and .json, in this case name. So I came up with something like this:

> var url = "/dir/name.json";
> var pattern = /\/\w+\./
> url.match(pattern) 
[ '/name.', index: 4, input: '/dir/name.json' ]

but I just want to match name and not /name.

Of course there is another way to do this by using substr:

> var url = "/dir/name.json";
> url.substr(5, url.length-10)
'name'

but I wonder if I can do this using Regex

2
  • 1
    url.match( /dir\/(.*?)\./ )[1] Commented Mar 31, 2015 at 5:37
  • 1
    You can use /\/dir\/(\w+)\.json/ and name will be in the first captured group Commented Mar 31, 2015 at 5:38

2 Answers 2

2

Assuming the dot is the discriminant (so it cannot be present in dir names...)

x = (/\w+(?=\.)/).exec("/dir/name.json")

could do it.

The syntax (?=...) describes a sub-expression that must match but that is not considered "consuming characters" so the meaning of the whole regexp is "a non-empty sequence of word characters followed by a dot (not considering it part of the match)".

The technical name is "positive look-ahead zero-width assertion".

If the dot could be present in directory names something that could work is:

x = (/\w+(?=\.\w*$)/).exec("/dir.1/dir.2/name.json")

because the lookahead now wants to be sure that after the dots there are only word characters (if any) and then the string ends.

Finally, if the extension could be missing completely:

x = (/\w+(?=\.\w*$|$)/).exec("/dir.1/dir.2/name.json")

works also for "dir.1/dir.2/name".

Sign up to request clarification or add additional context in comments.

Comments

2

Try this:

alert("/dir/name.json".match(/\/(\w+)\./)[1])

alert("/dir/name.json".split("/").pop().split(".").shift())

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.