Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript how to escape backslash character

Tags:

typescript

I would like to create a regular expression in Typescript to match the decimal separator character followed by a sequence of 0s in a string. For example, if the decimal separator is ., then the expression I've come up with is:

/\.0+\b/g

Since the decimal separator is determined at run-time based on locale, I am constructing my expression in code, with the decimalSeperator as a variable:

 "/\\" + decimalSeperator + "0+\b/"; 

My intention is that the double backslash characters will be escaped to a single backslash character.

However, the double backslash characters are not being escaped in my compiled JavaScript:

"/\\" + decimalSeperator + "0+\b/"

Yet if I used a single backslash, the code won't compile due to the " being escaped:

"/\" + decimalSeperator + "0+\b/"; 
  • error TS1005: ',' expected.
  • error TS1127: Invalid character.
  • error TS1002: Unterminated string literal.

Is this a bug with Typescript or am I doing something wrong?

Thanks

like image 901
Bojin Li Avatar asked Oct 20 '15 01:10

Bojin Li


1 Answers

However, the double backslash characters are not being escaped in my compiled JavaScript

That is by intention. The compile time JavaScript will be very similar to pre compile TypeScript. "\\" will compile to "\\" . However at runtime "\\" will be \ i.e. a single back slash.

console.log("\\"); // prints "\"
like image 184
basarat Avatar answered Sep 23 '22 10:09

basarat