0

I am new to javascript and regular expressions.So sorry if this question looks silly.

I want to use negative lookahead to find last matched word in a string. Pattern is dynamic i.e. it may change.

Ex Find "foo" in "this foo is not same foo" here regex should return index of last "foo". To find it I used foo(?!.*foo) negative lookahead. But I need to keep "foo" in variable so that i can find other pattern also.

I am trying to use RegExp() constructor to use variables but unable to find ways in which i can use negative lookahead syntax.So is there any way to use negative lookahead in RegExp constructor ? If yes, what is it ?

Bhuwan
  • 225
  • 5
  • 15
  • 1
    `var s = "foo"; var rx = new RegExp(s + "(?!.*" + s + ")");` – Wiktor Stribiżew Dec 01 '16 at 10:20
  • thanks Wiktor but it seems my regex is not working properly. – Bhuwan Dec 01 '16 at 11:27
  • Describe the real issue then. Right now, as you see, your question is about how to build a regex with variables. – Wiktor Stribiżew Dec 01 '16 at 11:28
  • yes..Actually I want to find last matched word in a sentence.To do this , i am trying to use negative lookahead. I am using foo(?!.*foo) to do this but it is not returning correct index. This functionality is same as previous button functionality in search box of chrome (which find previous word if you click on up arrow). – Bhuwan Dec 01 '16 at 11:31
  • You are speaking about another topic, not what you asked in the OP. Please re-write the question using the code that fails. – Wiktor Stribiżew Dec 01 '16 at 11:33
  • i am using search(regex) in javascript to search for previous word – Bhuwan Dec 01 '16 at 11:33

0 Answers0