2

I am trying to add a backslash to the following list of allowed characters. It must be used & passed-in as it is shown in the RegExp string below:

I have tried escaping it, but to no avail:

expandedText: function (e) {

        var regex = new RegExp("^[\\w., #&/-]+$");
        var key = String.fromCharCode(!e.charCode ? e.which : e.charCode);

        if (!regex.test(key)) {
            event.preventDefault();
            return false;
        }
    }
Prisoner ZERO
  • 13,848
  • 21
  • 92
  • 137
  • The first escape character may be getting caught by PHP before getting to the RegEx engine. Try four backslashes? – Worthwelle Jun 06 '18 at 18:49
  • That is, your intent is to capture word characters with `\w`, but it is not capturing word characters? Or are you trying to capture backslash and also capture a literal `w`? Or a backslash and all word characters? – apsillers Jun 06 '18 at 18:50
  • @apsillers - yes, it is capturing word characters fine. I need Backslashes too, please. – Prisoner ZERO Jun 06 '18 at 18:51
  • @Prisoner ZERO I think your looking for something like this: RegExp("^[\\\w., #&/-]+$") – hajile78 Jun 06 '18 at 18:55
  • @hajile78 No, that's not correct. That creates exactly the same RexEx as the one that OP already has. – JLRishe Jun 06 '18 at 18:59

2 Answers2

3

Because you're creating the RegEx from a string literal, the double backslash is being interpreted as an escaped backslash within the string and you're winding up with this RegEx:

^[\w., #&/-]+$

This matches word characters, but backslashes are nowhere to be found.

The solution: escape both backslashes, and add one for the \w, resulting in six backslashes:

var regex = new RegExp("^[\\\\\\w., #&/-]+$");

Or even better, use a regular expression literal and only use three backslashes:

var regex = /^[\\\w., #&/-]+$/;
JLRishe
  • 99,490
  • 19
  • 131
  • 169
3

In addition to escaping the backslash for the regex expression, you must also escape each backslash within the string literal. That is, the string literal

"\\"

evaluates to a one-character string sequence consisting of a single backslash. Since you need two backslashes to express a single backslash in your regular expression, you need four backslashes in your string literal to express two backslashes in your regular expression:

"\\\\"

This expresses a two-character sequence in the regular expression: one backslash, preceded by an escaping backslash, to fill out out regular expression. That is, these two expressions (using a regex literal and the RegExp constructor) are equivalent:

/\\/
new RegExp("\\\\")

Each of these regular expression objects will match a single backslash.

Using a the RegExp constructor, you can do: new RegExp("^[\\\\\\w., #&/-]+$"); however, it seems like a regex literal would be cleaner and shorter with no disadvantages (as you don't dynamically build your regex using a varying string):

var regex = /^[\\\w., #&/-]+$/
apsillers
  • 112,806
  • 17
  • 235
  • 239