Reputation: 19
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
Upvotes: 0
Views: 1399
Reputation: 5067
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.
Upvotes: 1
Reputation: 39355
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);
Upvotes: 2