0
txt = '<a class="info" href="/some/link" original-title="hello world <br/> Monday <br/> 2 days <br/> Test"> 10 </a>';

var pattern = /\s\d+/;
var parsed_data = parseInt((txt.match(pattern)||['0'])[0]);

Got this regex pattern from some example. I am trying to parse the text i.e. value 10 from the anchor tag. But the value obtained is 2.

EDIT: I am using datatables to populate the tables. And problem is the string i.e. txt is a row element, extracted from table using loop and need to add these values e.g.

var parsed_data += parseInt((txt.match(pattern)||['0'])[0]);
4

2 回答 2

4

It is a very bad idea to parse a html content with regex, in this case use jQuery to fix it

var txt = '<a class="info" href="/some/link" original-title="hello world <br/> Monday <br/> 2 days <br/> Test"> 10 </a>';

var parsed_data = parseInt($(txt).text(), 10);
console.log(parsed_data)

Demo: Fiddle

于 2013-11-07T08:40:11.440 回答
0

You could have something like that:

var txt = '<a class="info" href="/some/link" original-title="hello world <br/> Monday <br/> 2 days <br/> Test"> 10 </a>';

var pattern = /.*>\s*(\d+)/;
var matches = txt.match(pattern);
var parsed = matches ? +matches[1] : 0;

However, this regexp takes just the last digit inside a tag (>): if you want to have something more precise, you should parse the HTML using the DOM – that is more expensive. It's really depends by what is your data, if you always have such format, you don't need the DOM.

于 2013-11-07T08:56:52.147 回答