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?

3
  • remove the '/' at the start and ending of the pattern. Commented Mar 10, 2014 at 11:56
  • I tried with removing '/' but it didn't work. Commented Mar 10, 2014 at 11:57
  • 1
    @Pakspul - the / at the start and end are part of JS's regex literal syntax, not part of the actual pattern. Commented Mar 10, 2014 at 11:59

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

1 Comment

@GaneshKunwar Huh? I didn't give a solution in this answer. I was explaining why your regex didn't work.
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.

2 Comments

Thanks Casimir for your answer, but it gives two words including 'on'. I need a word after 'on'.
@GaneshKunwar: this is the reason why you must extract the capturing group from the match result. Take a look at this topic: stackoverflow.com/questions/432493/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.