Javascript Regex Match Only Inside Parenthesis
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 parent
Solution 1:
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);
Solution 2:
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.
Post a Comment for "Javascript Regex Match Only Inside Parenthesis"