-2

My string should be in the IRC command format : "/add john".

So, i created this Regex :

var regex = /^\/add ([A-Za-z0-9]+)$/
var bool = regex.test('\/add user1');
alert(bool);

The problem is either I use /***/ or RegExp syntax, if I set a backslash at the beginning of my string (like in my example above), my alert pop up show "true" and I don't want that.

I code in Javascript

mtnp
  • 314
  • 7
  • 24
  • 1
    Backslash in a string literal is an escape sequence, not an actual backslash. `"\/" === "/"` – ASDFGerte Nov 21 '19 at 17:33
  • So, how can I do to reject this string '\/add user1' ? Two separate condition tests ? – mtnp Nov 21 '19 at 17:45
  • 1
    `'\/add user1' === '/add user1'` – ASDFGerte Nov 21 '19 at 17:47
  • I understand now, I didn't know that backslash is automatically deleted in a string type. See: https://stackoverflow.com/questions/10041998/how-can-i-use-backslashes-in-a-string Thanks, problem solved. – mtnp Nov 21 '19 at 17:55

1 Answers1

0

You can use String.raw to make sure that the backlash is not removed when testing your input:

var regex = /^\/add ([A-Za-z0-9]+)$/
var bool = regex.test(String.raw`\/add user1`);
alert(bool);

You can play with this code here: https://jsbin.com/ziqecux/25/edit?js

Yves Gurcan
  • 1,096
  • 1
  • 10
  • 25