8

I'm trying to convert following expression to "new Regexp()" style:

http://jsfiddle.net/HDWBZ/

var Wyrazenie = /\btest[a-z]*/g;

I'm really confused with it and have no idea how to fix it. Below is what I've done but obviously it doesn't work.

var Wyraznie = new RegExp("\btest[a-z]*","g");

Also have a question how would it look if instead of "test" I would use variable?

mik.ro
  • 4,381
  • 2
  • 18
  • 23
  • 1
    Please ask only one question at a time. Create a separate SO question for each separate question (sounds logical, right?). – O. R. Mapper Dec 19 '12 at 17:41

1 Answers1

11

You should use this instead...

new RegExp("\\btest[a-z]*", "g");

... as \b will be interpolated into a single (slashless) character when JavaScript parser works through the corresponding string literal. The solution is to escape slash itself.

DEMO: http://jsfiddle.net/HDWBZ/1/

VisioN
  • 143,310
  • 32
  • 282
  • 281
  • @raina77ow Thanks for the edit. You forestalled me :) – VisioN Dec 19 '12 at 17:43
  • thank you, works perfect! Regarding to second part: new RegExp("\\b"+test+"[a-z]*", "g");, where test is variable – mik.ro Dec 19 '12 at 17:45
  • Thanks man it works poperly let myString = " Tata Nexon EV Tata" let myVariable = "Tata" let myReg = new RegExp("\\b"+myVariable , "g") let myMatch = myString.match(myReg) console.log(myMatch) – Arindam Sarkar Jun 02 '22 at 14:50