Alessandro Minoccheri
Alessandro Minoccheri

Reputation: 35973

Substring between two characters

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

Answers (3)

Denys Séguret
Denys Séguret

Reputation: 382454

You can use

var num = parseInt(yourString.match(/\[(\d*)\]/)[1], 10);

This returns 2 as a number.

Upvotes: 2

Andreas Louv
Andreas Louv

Reputation: 47137

var a = "image[2]",
    r = /\[([^\]]*?)\]/;

console.log(a.match(r)); // ["[2]", "2"]

var num = +(a.match(r)[1]); // 2

Upvotes: 2

dsgriffin
dsgriffin

Reputation: 68616

You can try using this: \[(.*?)\]

Upvotes: 1

Related Questions