2

i want to replace specific amount of white-spaces from a String at the beginning and i can use

replace(/^\s{2}/g,"");

and it works .but 2 should be changed according to a value of a variable .so i need to construct a new RegExp()

so i used

var lead=2;
var regex = new RegExp("\^\\s{" + lead + "}//g");
alert("regex  "+regex);

real output

 /^\s{2}\/\/g/

expected output

/^\s{2}/g

could you help me to fix this problem.tnx

Madhawa Priyashantha
  • 9,633
  • 7
  • 33
  • 60
  • 1
    @nhahtdh I don't think this question is duplicate of http://stackoverflow.com/questions/494035/how-do-you-pass-a-variable-to-a-regular-expression-javascript Even the answers on this question will not help to solve this problem – Tushar Jul 10 '15 at 06:19
  • yes it didn't .i'm not asking how to use variables in regex – Madhawa Priyashantha Jul 10 '15 at 06:20
  • @Tushar: Better dup: http://stackoverflow.com/questions/516917/javascript-regexp-objects – nhahtdh Jul 10 '15 at 06:39

3 Answers3

2

As the param to RegExp is the regex, you don't need the / delimiters. Use the flags as the second parameter to the RegEx() constructor.

var regex = new RegExp("^\\s{" + lead + "}", 'g');

Example:

var lead = 2;
var regex = new RegExp("^\\s{" + lead + "}", 'gmi');

alert(regex);

var str = '  Say My Name';
alert(str.replace(regex, ''));
Tushar
  • 85,780
  • 21
  • 159
  • 179
1
new RegExp("^\\s{" + lead + "}", "g");
Diode
  • 24,570
  • 8
  • 40
  • 51
-1

Try

"\^\\s{" + lead + "}\/g"

instead of

"\^\\s{" + lead + "}//g"

I think you wanted to escape the "/", but you accidently used "/" instead of "\".

red13
  • 427
  • 4
  • 12