Kapil gopinath
Kapil gopinath

Reputation: 1053

Javascript Regex to return only a range of items

I have a requirement were the regex expression should only return the immediate children of it's parent. For eg. If parent is denoted by classname "level-0", it's immediate children classname can be "level-0-0, level-0-1......,level-0-10" etc.

I have a regex in javascript that is intended to return only the immediate child, but it's not working. Please find the regex below.

$('tr').filter(function(){
  return this.className.match(/level-0[-\d+]{1,1}/)
}) // The result below.
[<tr class=​"fundRow level-0-0 child" style=​"display:​ table-row;​">​…​</tr>​, <tr class=​"fundRow level-0-0-0 child" style=​"display:​ table-row;​">​…​</tr>​, <tr class=​"fundRow level-0-0-0-0 child" style=​"display:​ table-row;​">​…​</tr>​, <tr class=​"fundRow level-0-0-0-1 child" style=​"display:​ table-row;​">​…​</tr>​, <tr class=​"fundRow level-0-0-1 child" style=​"display:​ table-row;​">​…​</tr>​, <tr class=​"fundRow level-0-1 child" style=​"display:​ table-row;​">​…​</tr>​]

Here the parent class is "level-0". What I am expecting is "level-0-0 ,level-0-1". In the regex "[-\d]+{1,1}", I am trying to specify that level-0 should be followed by a single occurrence of '-' followed by integer. But I am not able to restrict the occurrence.

Upvotes: 0

Views: 47

Answers (1)

Avinash Raj
Avinash Raj

Reputation: 174806

It would be like below,

/level-0-\d+\s/

Use word boundary if necessary.

/\blevel-0-\d+\s/

Upvotes: 2

Related Questions