Javascript Regex

Im very bad when it comes to javascript.

Anyone know how to get the keyword from a google url

Example url

http://www.google.com/search?q=javascript+regex+examples&ie=utf

want to extract javascript+regex+examples
in php would use

$url = 'http://www.google.com/search?q=javascript+regex+examples&ie=utf';
$phrase = preg_match("/q=(.*?)&/",$url, $m);
echo $m[1];

Anyone know how to use that regex in Javascript?

Thanks

Check out match and [URL=“https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/RegExp/exec”]exec. Give it a go and if you encounter problems post what you attempted. :slight_smile:

Hey that works awesome used


<script type="text/javascript">
str = "http://www.google.com/search?q=javascript+regex+examples&ie=utf";
re = /q=(.*?)&/i;
found = str.match(re);
document.write(found);
</script>

It outputs
q=javascript+regex+examples&,javascript+regex+examples

You guys know how just show it 1x?

Thanks for the reply man!

Hey this works!

<script type="text/javascript">
var myRe = /q=(.*?)&/g;
var str = "http://www.google.com/search?q=javascript+regex+examples&ie=utf";
var myArray;
while ((myArray = myRe.exec(str)) != null)
{
  var msg = myArray[0] ;
  alert(msg);
}
</script>

Thanks so much :slight_smile:

It alerts
q=javascript+regex+examples&

What you’re getting there is the full match.

If you only want the captured group, use myArray[1] instead for
javascript+regex+examples

The things you can find out online.

Never fails to amaze me lol

Hey thanks so much for that last adjustment

works 100% awesome now