Simple RegEXP HELP!

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
User avatar
J0kerz
Forum Commoner
Posts: 37
Joined: Fri May 29, 2009 2:51 pm

Simple RegEXP HELP!

Post by J0kerz »

Hey guys,

I am having trouble with a Javascript regular expression. I am using the match function and results output are wrong.

Here is my code:

Code: Select all

<script language="javascript" type="text/javascript">

string = 'addfriend\.php\?id=1\\\" |||||| addfriend\.php\?id=2\\\" |||||| addfriend\.php\?id=3\\\" ';

result = string.match(/addfriend\.php\?id=(\d*)\\\"/gi);


for (i=0; i < result.length; i++) {


	document.write(result[i] + '<br>');

}


</script>
The result are:

addfriend.php?id=1\"
addfriend.php?id=2\"
addfriend.php?id=3\"


I would like the result to only be:

1
2
3

What is wrong with my code? How could it only select the id number?

Thanks guys!
JakeJ
Forum Regular
Posts: 675
Joined: Thu Dec 10, 2009 6:27 pm

Re: Simple RegEXP HELP!

Post by JakeJ »

try: '/(?<=addfriend.php\?id=)(.*?)(?=\\)/'

This expression does a positive look-behind for 'addfriend.php\?id=' then find any value, the does a positive look ahead for a slash. The look-ahead and look-behind are excluded from the actual search results.



Please note, I didn't test it.
User avatar
tr0gd0rr
Forum Contributor
Posts: 305
Joined: Thu May 11, 2006 8:58 pm
Location: Utah, USA

Re: Simple RegEXP HELP!

Post by tr0gd0rr »

JavaScript String#match does not work that way. You may be looking for something like PHP's preg_match_all(). This post shows an example. Also check out Prototype JavaScript's String#scan.
User avatar
McInfo
DevNet Resident
Posts: 1532
Joined: Wed Apr 01, 2009 1:31 pm

Re: Simple RegEXP HELP!

Post by McInfo »

This is similar in that it does a global match and then local matches.

Code: Select all

var str = 'addfriend\.php\?id=1\\\" |||||| addfriend\.php\?id=2\\\" |||||| addfriend\.php\?id=3\\\" ';
var ids = [];
try {
    str.match(/addfriend\.php\?id=\d+/gi).forEach(function(s){ ids.push(s.match(/\d+/)[0]); });
} catch (e) { /* TypeError */ }
/* ids = ["1", "2", "3"] */
If any of your target browsers do not support Array.forEach(), you can use a loop instead or extend Array.prototype.
Post Reply