Shub
Shub

Reputation: 2704

Split ignoring part of regex

My goal is to get the length till the nth occurrence of <br> tag in javascript so I am splitting them up.

I am trying regex

((.|\s)*?<br\s?/?>){2}  //2 is the max number of lines(br tags) allowed.

While this is working fine in regexBuddy

but the string is splitted into multiple parts ignoring the <br\s?/?> part in browser. you can view a fiddle here

What am I doing wrong

Upvotes: 0

Views: 84

Answers (2)

Tim Mullen
Tim Mullen

Reputation: 624

The issue is that you are using the split() method, which will split the string up in to pieces based on the regular expression. This will not include your regular expression match. In your case the first section of the string matches your regular expression, so you would have an empty string at index 0 and everything after the regular expression match in index 1.

You should try to use the match() method instead, which will return an array of the pieces of the string that matched your regular expression.

var str=$('#op').html();
console.log(str.match(/(([\s\S])*?<br\s?\/?>){2}/i)[0].length);

See code.

Upvotes: 0

ebyrob
ebyrob

Reputation: 674

Wouldn't exec make more sense than split in this case?

var str=$('#op').html();
var match = /((.|\s)*?<br\s?\/?>){2}/i.exec(str);
if( match )
  console.log(match[0].length);

Upvotes: 1

Related Questions