Reputation: 35973
I have a simple string like this:
image[2]
I want to get the number between []
, in this case have to return 2
.
What is a good regular expression to do this in JavaScript? I have tried with substring
but I want to apply a regular expression.
Upvotes: 0
Views: 78
Reputation: 382454
You can use
var num = parseInt(yourString.match(/\[(\d*)\]/)[1], 10);
This returns 2
as a number.
Upvotes: 2
Reputation: 47137
var a = "image[2]",
r = /\[([^\]]*?)\]/;
console.log(a.match(r)); // ["[2]", "2"]
var num = +(a.match(r)[1]); // 2
Upvotes: 2