Reputation: 2704
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
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);
Upvotes: 0
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