0

I have an data.url string. I want to get some data from it with the following regex

    var filename = data.url.match(/file=(.+)&/gi);

All I want is the data inside the parenthesis -a file name actually- but what I get back is "file=example.jpg&". Why is this happening? Shouldn't only the the matches found in the parentheses be returned? How can I get rid of those unnecessary characters? Thanks

2 Answers 2

2

Javascript returns both the whole matched pattern(usually known as group-0) along with the other matched groups. You can use this one:

var filename = /file=(.+)&/gi.exec(data.url).slice(1);
Sign up to request clarification or add additional context in comments.

Comments

1

Use

var filename = data.url.match(/file=([^&]+)/i)[1];

Example:

"file=example.jpg".match(/file=([^&]+)/i)[1] == "example.jpg"
"file=example.jpg&b=ttt&c=42".match(/file=([^&]+)/i)[1] == "example.jpg"
"http://example.com/index.php?file=example.jpg&b=ttt&c=42".match(/file=([^&]+)/i)[1] == "example.jpg"

match() returns an array with the first searched group at the second place, i.e. at match(...)[1].

Note: The result of the above code will be a String. If you still want to have a singleton array with your filename as the only element, then you should take the solution of @Sabuj Hassan.

2 Comments

Hmm, if you're using [^&]+, then you can safely remove the &? at the end. Unless OP specifically wants to match if there's a &, in which case, you shouldn't use the ?.
@Jerry: Thanks! I will rewrite my solution to the shorter regex... ;-)

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.