user7255640
user7255640

Reputation:

Get all strings between 2 characters

I have the following string:

"The length must be between <xmin> and <xmax> characters"

I'm trying to get all Words/strings that is between <> But with my code I only get the following:

xmin> and <xmax

This is my code:

var srctext = "The length must be between <xmin> and <xmax> characters";
    var re = srctext.match(/\<(.*)\>/).pop();
    console.log(re);

How can i get both xmin and xmax out?

Upvotes: 3

Views: 981

Answers (1)

Pranav C Balan
Pranav C Balan

Reputation: 115222

Use non-greedy regex to match the least.

var srctext = "The length must be between <xmin> and <xmax> characters";
var re = srctext.match(/<(.*?)>/g);
console.log(re);

or use negated character class

var srctext = "The length must be between <xmin> and <xmax> characters";
var re = srctext.match(/<([^>]*)>/g);
console.log(re);


UPDATE : To get the captured value when regex contains g(global) flag use RegExp#exec method with a while loop.

var srctext = "The length must be between <xmin> and <xmax> characters",
    regex=/<([^>]*)>/g,
    m,res=[];

while(m=regex.exec(srctext))
  res.push(m[1])
  
console.log(res);

Upvotes: 4

Related Questions