Reputation:

Javascript does not support positive lookbehind

I have the following regular expression in .Net

(?<=Visitors.{0,100}?"value">)[0-9,]+(?=</div>)

and the following text

<div class="text">Visitors</div> <div class="value">14,000,000</div>
<div class="text">VisitorsFromItaly</div> <div class="value">15,200</div>

I specify in the regex either "Visitors" or "VisitorsFromItaly" and I get the number that specific number of Visitors.

I want to do this in javascript but without using any .replace methods. I just need a plain simple javascript regex. I am new to javascript regex so I have no idea how to convert it. It says that javascript does not support lookbehind and that is the thing that is making my .Net regex working.

Any help would be appreciated. Thanks a lot in advance!!!

Upvotes: 2

Views: 1974

Answers (3)

Vilmondes Eracton
Vilmondes Eracton

Reputation: 11

Try it:

var regex = /visitors<\/div>\s?<div class="value">([\d,]+)/i;

var input = '<div class="text">Visitors</div> <div class="value">14,000,000</div><div class="text">VisitorsFromItaly</div> <div class="value">15,200</div>
';

if(regex.test(input)) { 
  var match = input.match(regex); 
  alert(match); 
} else { 
  alert("No matches found!"); 
}

Upvotes: 1

Platinum Azure
Platinum Azure

Reputation: 46193

I'm not sure I understand you... Do you really need a lookbehind assertion?

Can't you just match something like the following?

myRegex = /Visitors.{0,100}"value">([0-9,]+)/; // or with /g modifier on the end?
myMatches = myRegex.exec(stringToMatch);

myMatches[0] contains the entire matched string. myMatches[1] and higher would contain the first, second, etc. capture groups, denoted by parentheses in the regex. In this case, myMatches[1] contains the number.

Since you don't seem to need to match anything else before the numbers (besides Visitors etc.), I don't think you'll need a lookbehind assertion at all.

Upvotes: 2

scunliffe
scunliffe

Reputation: 63588

are you getting this data as a string? or do you have access to a DOM object (e.g. AJAX response)?

If you have access to the latter, I wouldn't bother with regex.

Upvotes: 0

Related Questions