JavaScript and client side scripting.
Moderator: General Moderators
J0kerz
Forum Commoner
Posts: 37 Joined: Fri May 29, 2009 2:51 pm
Post
by J0kerz » Fri Apr 29, 2011 2:50 pm
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
Post
by JakeJ » Thu May 05, 2011 3:57 am
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.
McInfo
DevNet Resident
Posts: 1532 Joined: Wed Apr 01, 2009 1:31 pm
Post
by McInfo » Fri May 06, 2011 3:16 pm
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.