Ajax html response fetch particular data

Hi

success: function(data) {
                $("#result").html(data);
                      }

The above code fetches and displays the result as

Product added to basket. You have now <span id="number">5</span> products in basket

How can i just fetch only “5” from the result.

and update the html content of div with id=“items” with “5”

Thanks
Vineet

var thisNum = data.match(/<\s*span[^>]*>(.*)<\s*[^>]*>/gi);

thisNum will be a comma-delimited array that returns the regex match of the whole string as the first part [0] and the backreference (between parenthesis) as the second part [1]. So, thisNum[1] should be the value "5".

UPDATE: If there are more than one instance of span tags within the string, there will be more than two items in the array… the second position through nth position of the array will be each instance of a value sandwiched between span tags.

LINK

HTH,

:slight_smile:

1 Like

Hi Wolfshade

alert (thisNum) gives result as

<span id="numbers">5</span>

But alert(thisNum[1]) gives result as “undefined”

what am i writing wrong ??

vineet

Odd… and that’s a good question. I don’t know. thisNum[1] should be 5.

Try removing the g flag from after the last / (so it will be /i instead of /gi.) See if that fixes it.

HTH,

:slight_smile:

Hi Wolfshade

That did the trick.

all result fine now.

But whats the difference in /i and /gi ??

Thanks
Vineet

Honestly, I’m not entirely sure, as I don’t use match() often.

But, according to the MDN page for match(), the g flag will return only the matched regex substring (ie, the whole match.) Whereas if you don’t use the g flag, the array will contain captures (aka ‘backreference’, the part within the parenthesis.)

HTH,

:slight_smile:

I thought that without the global flag only the first match was returned.
i.e. if there were multiple <span> tags only the first one.

I’m also thinking that using
(\d*)
would be better than using
(.*)

I don’t know from an efficiency standpoint which is faster. Outside of that, it’s six-and-a-half-of-one, half-a-bakers-dozen-of-the-other. :smile:

:slight_smile:

(\d*) is far better than (.*) for the latter allows any old rubbish through.

When comparing choices, it’s preferable to use the more restrictive regex.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.