Kim
Kim

Reputation: 2777

regex match different with jQuery

I am getting different results from regex match when using both regular JS and jQuery v1.4.2 and unable to figure out why. Only match string should be returned. I use jQuery to grab the whole table via the parent ID using .html(). textToSearch is shorten.

textToSearch = '<tr><th colspan="5">my match with spaces here (<a href=';
pattern = /(?=<th colspan="\d">).*(?= \()/i;
expected_result = 'my match with spaces here';

var match = textToSearch.match(pattern);

In regular JS I get expected result, but in jQuery I get 'my match with spaces here'. Am I doing something wrong is jQuery messing things up ?
Maybe there is a better way getting the expected result ?

Edit: Solution below.

var pattern = /.*(?= \()/;
var t = $('#'+id+' th[colspan]').text();
$('#'+targetid).text(t.match(pattern)[0]);

Upvotes: 0

Views: 438

Answers (1)

Andy E
Andy E

Reputation: 344537

jQuery's html() will not return the html in the format you're expecting above, and it may even differ between browsers. The string returned is constructed from the browser's representation of the DOM tree, and so will look nothing like the "view source" feature of most browsers. Parsing HTML with regular expressions isn't a great idea for this reason (and others).

It's unclear to me why you're using a regular expression. If you're grabbing the html with html(), you may as well just filter the nodes and grab their text instead. It would be a much more robust solution. For instance, the following code may do the job for you:

var result = $("table th[colspan]")[0].firstChild.nodeValue;

Or perhaps you want the entire text for that <th> element?

var result = $("table th[colspan]").text();

Either way, there's almost certainly a better way to attain the match you're after without using regular expressions.

Upvotes: 2

Related Questions