I am having a little trouble with regular expression.
I want to match a regular expression in a sentence.
Example :
John has two candy ::123::
and i am using this code to look for it:
var getid = x$('div').html().match(/::([^:]+)::/g);
To get the 123 our of the sentence.
So what’s my problem here?
I kept on getting an undefined value for getid var.
The problem is the
gflag. You don’t use it withString#match. Remove it and it works fine (live copy | source):If you want to find all of the matches in the text, use
RegExp#execand a loop (and thegflag) (live copy | source):(For greater clarity, you might use
…since having an assignment in a test looks like a
=instead of==typo; but it comes to the same thing other than readability.)Re your comment below asking about
x$(this), it should make any difference. Here are the above examples reworked to usex$(this):