1

I know that I can use case insensitive approach as follows:

var name = "test A/c";
{name: new RegExp('^'+name+'$', "i")}

Now I want to escape backslash in above expression. I know how to escape backslash:

/\//ig;

But I dont know how to use these two patterns in combination with each other.

KernelPanic
  • 600
  • 8
  • 19
Vishal
  • 6,238
  • 10
  • 82
  • 158

3 Answers3

1

You could do it using the following way ...

var name = "test A/c".replace(/(?=\/)/g, '\\\\');
{name: new RegExp('^'+name+'$', "ig")}
m87
  • 4,445
  • 3
  • 16
  • 31
  • I have given the example here. But in reality, the value of variable name will be coming from database. – Vishal Mar 09 '17 at 06:29
  • You should explain why the double slashes are necessary. `Teach a man to fish`... – Regular Jo Mar 09 '17 at 06:29
  • still getting the same result. Please take a look at this post for more details: http://stackoverflow.com/questions/42680530/escape-forward-slash – Vishal Mar 09 '17 at 06:43
  • 1
    At last found the mistake. new RegExp() function does not need to escape backslash. My mistake was, I was sending this value from url and thus it was counted as new parameter after slash. Thank you for helping. – Vishal Mar 09 '17 at 07:57
1

You can use replace in second expression.

var name = "test A/c"; {name: new RegExp('^'+name.replace(/\//g,'\\/')+'$', "i")}

Kamuran Sönecek
  • 3,293
  • 2
  • 30
  • 57
1

Take a look at this post Escaping Strings in JavaScript and check if this is what you are looking for.

quoting from above link:

function addslashes( str ) { return (str + '').replace(/[\\"']/g, '\\$&').replace(/\u0000/g, '\\0'); }

Community
  • 1
  • 1
  • Good job on citing relevant information, though thi is more of a comment. You should copy relevant text here. If that url is changed, the link becomes useless. – Regular Jo Mar 09 '17 at 06:43
  • At last found the mistake. new RegExp() function does not need to escape backslash. My mistake was, I was sending this value from url and thus it was counted as new parameter after slash. Thank you for helping. – Vishal Mar 09 '17 at 07:58