0

I have a regular expression to find the next word of given word 'on' in string for php:

(?<=\bon\s)(\w+)

It works perfectly for PHP but for js it gives following error:

Uncaught SyntaxError: Invalid regular expression: /(?<=\bon\s)(\w+)/: Invalid group

What is the equivalent regex for javascript?

nnnnnn
  • 147,572
  • 30
  • 200
  • 241
Ganesh Kunwar
  • 2,643
  • 2
  • 20
  • 36

2 Answers2

2

(?<=\bon\s) is a positive lookbehind. PHP's regular expression engine (PCRE) supports those, but JavaScript's regular expression engine doesn't.

While it's not possible to write an exactly similar regex, you can still achieve this using the following regex:

\bon\s(\w+)

Unlike in the original regex, \bon\s consumes characters. But you can still extract the results using a capturing group (\w+).

Usage:

var str = 'foo on bar';
var matches = str.match(/\bon\s(\w+)/);
var result = matches[1] // bar

Fiddle

Amal Murali
  • 75,622
  • 18
  • 128
  • 150
1

As Amal Murali explains it, there is no equivalent with Javascript regex. However you can write:

\bon\s(\w+)

and extract the first capturing group.

Casimir et Hippolyte
  • 88,009
  • 5
  • 94
  • 125
  • Thanks Casimir for your answer, but it gives two words including 'on'. I need a word after 'on'. – Ganesh Kunwar Mar 10 '14 at 12:14
  • @GaneshKunwar: this is the reason why you must **extract** the capturing group from the match result. Take a look at this topic: http://stackoverflow.com/questions/432493/how-do-you-access-the-matched-groups-in-a-javascript-regular-expression – Casimir et Hippolyte Mar 10 '14 at 12:15