Jim Blackler
Jim Blackler

Reputation: 23169

What explains the different treatment of special characters in regular expressions?

Testing in Chrome 10 Developer Tools console:

> str = "\t";
  " "
> JSON.stringify(str)
  ""\t""
> str.replace(/\t/g,"\\t")
  "\t"

All good. The regular expression was able replicate part of the JSON.stringify behavior and identify the tab character.

Now let's swap out \t for \b throughout:

> str = "\b";
  ""
> JSON.stringify(str)
  ""\b""
> str.replace(/\b/g,"\\b")
  ""

In this case replace couldn't find the backspace character.

So, my esteemed SO colleagues, could someone lend me a clue and account for the difference in behaviour?

Upvotes: 2

Views: 188

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1075069

The escape sequences in regular expressions are not identical to the ones in string literals. In a regular expression, \b matches a word boundary. \t happens to be the same in regular expressions and string literals.

MDC has a fairly good writeup of these, although of course there's nothing like going to the specification.

Upvotes: 4

Related Questions