Odd behavior of escape characters in Typescript

Looking for help with a query similar to the one referenced here.

I am new to TypeScript and front end development. Currently using an Angular form to collect user input, which may contain regex.

For example:

The input from the form, stored in this.expressions, can consist of multiple expressions separated by a new line character.

this.rewrite_object = []
this.expressions = "s|.*|{{ date | replace('-', '') }}\"/apps/data/{{ date | replace('-', '/') }}"
this.rewrite_array = this.expressions.split('\n')
console.log("******************Print after split******************")
console.log(this.rewrite_array)
if (this.rewrite_array.length > 0) {
   for(var i = 0;i<this.rewrite_array.length;i++) { 
      if (this.rewrite_array[i]) {
        console.log("******************Print before adding to array******************")
        console.log(this.rewrite_array[i])
        this.rewrite_object.push({ "expression": this.rewrite_array[i] });
        console.log("******************Print rewrite object******************")
        console.log(this.rewrite_object)
      }
   }
}

The output shows that the escape character is disappearing.

******************Print after split******************                                                                                       
[                                                                                                                                           
  `s|.*|{{ date | replace('-', '') }}"/apps/data/{{ date | replace('-', '/') }}`                                                            
]                                                                                                                                           
******************Print before adding to array******************                                                                            
s|.*|{{ date | replace('-', '') }}"/apps/data/{{ date | replace('-', '/') }}                                                                
******************Print rewrite object******************                                                                                    
[                                                                                                                                           
  {                                                                                                                                         
    expression: `s|.*|{{ date | replace('-', '') }}"/apps/data/{{ date | replace('-', '/') }}`                                              
  }                                                                                                                                         
] 

I considered using \ to escape the escape character itself, but encountered errors during compilation.

test.ts:2:70 - error TS1136: Property assignment expected.                                                                                  
                                                                                                                                            
2 this.expressions = "s|.*|{{ date | replace('-', '') }}\\"/apps/data/{{ date | replace('-', '/') }}"                                       
                                                                       ~                                                                    
                                                                                                                                            
test.ts:2:98 - error TS1128: Declaration or statement expected.                                                                             
                                                                                                                                            
2 this.expressions = "s|.*|{{ date | replace('-', '') }}\\"/apps/data/{{ date | replace('-', '/') }}"                                       
                                                                                                   ~                                        
                                                                                                                                            
test.ts:2:100 - error TS1002: Unterminated string literal.                                                                                  

2 this.expressions = "s|.*|{{ date | replace('-', '') }}\\"/apps/data/{{ date | replace('-', '/') }}"
                                                                                                     


Found 3 errors.

I need to find a way for the quotation marks to work as intended with TypeScript, as I have to save this information in a database after collecting it from customers.

Answer №1

To get a backslash and double quote in your final string, you must escape them properly: use \\\" instead of just \".

The first backslash will escape the second one, resulting in a single literal backslash in the output. The third backslash is used to escape the double quote so it appears as part of the string.

this.expressions = "s|.*|{{ date | replace('-', '') }}\\\"/apps/data/{{ date | replace('-', '/') }}"

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Comparing Input and Output Event Binding

Can you provide reasons why using @Output for events is more advantageous than passing an @Input function in Angular 2+? Utilizing @Input: Parent Template: <my-component [customEventFunction]=myFunction></my-component> Inside parent-compone ...

What is the best way to utilize a tsconfig "alias path" to import an @ngModule along with other definitions?

Repository Link: https://github.com/andreElrico/mono-repo-test Stackblitz Example: https://stackblitz.com/github/andreElrico/mono-repo-test (noop; only to navigate smoothly) Assume the structure below: root/ ├── projects/ │ ├── app1 │ ...

Tips for displaying or concealing a div using Angular Js

I have set up two div elements with a dropdown control in one named div1. I am looking to hide div2 until a value is selected in the dropdown. How can I show or hide a div based on ng-change, ensuring that div2 remains hidden until a value is selected? Cod ...

Are generic constraints leading to type inference selecting the incorrect candidate?

TypeScript Version: 2.6.0-dev.20170826 and 2.4.2 I'm questioning whether I've encountered a TypeScript inference bug or limitation, or if my code is simply incorrect. If the code is valid and it's an issue with type inference, I will repor ...

Constructing an Angular 2 application using a solo TypeScript file that is compiled individually

At the moment, I am in the process of developing a Chrome Extension using Angular 2. The application includes a background.js file which handles the functionality for a long-running task that operates while the extension is active. Currently, this backgrou ...

How can we direct the user to another tab in Angular Mat Tab using a child component?

Within my Angular page, I have implemented 4 tabs using mat-tab. Each tab contains a child component that encapsulates smaller components to cater to the specific functionality of that tab. Now, I am faced with the challenge of navigating the user from a ...

What causes the "Error: method not allowed" message to appear when attempting to send a "DELETE" request from a Next Js component? (The POST method is

This is my first time on this platform, and I'm currently following a tutorial from Javascript Mastery to create a clone of a thread application. After watching the entire video and building the basic functionality based on it, I decided to enhance th ...

Leveraging Typescript Definitions Files from Definitely Typed with an Outdated Typescript Version

I've been struggling with integrating third party React component libraries into my project that uses Typescript 1.8.10 along with React and Redux. Specifically, I've been attempting to use React Date Picker, but have encountered issues due to th ...

When utilizing the catch function callback in Angular 2 with RxJs, the binding to 'this' can trigger the HTTP request to loop repeatedly

I have developed a method to handle errors resulting from http requests. Here is an example of how it functions: public handleError(err: any, caught: Observable<any>): Observable<any> { //irrelevant code omitted this.logger.debug(err);//e ...

How can I utilize a callback in TypeScript when working with interfaces?

Can someone guide me on how to implement an interface in typescript with callback function? interface LoginCallback{ Error: boolean, UserInfo: { Id: string, OrganizationId: string } } interface IntegrationInterface { Ini ...

Utilize the term "export const" twice when declaring variables to assign value

const foobar = { foo: 'hello', bar: this.foo }; The code isn't working as expected, returning "undefined". Any suggestions on how to properly access it? ...

"Utilizing the `useState` function within a `Pressable

Experiencing some unusual behavior that I can't quite figure out. I have a basic form with a submit button, and as I type into the input boxes, I can see the state updating correctly. However, when I click the button, it seems to come out as reset. Th ...

Animating sprites using TypeScript

I've been tackling the development of a small Mario game lately. However, I'm facing some difficulty when it comes to animating sprites. For instance, I have a mario.gif file featuring running Mario (although he's not actually running in th ...

What is the best way to bring in a variable initialized by an IIFE from a JavaScript file into a TypeScript class?

I'm currently working towards integrating the steelseries.js library (found at https://github.com/HanSolo/SteelSeries-Canvas) into a Grafana plugin built with React. It's quite a complex task, but I'm up for the challenge. Right now, my ma ...

Displaying an error message in a spreadsheet cell

Issue The problem arises when viewing the exported excel file where undefined is displayed. However, upon investigation, there are no empty array indexes causing this confusion. Solution Attempt const joinDate = new Date(obj.date); let snap = [ obj. ...

Exploring the capabilities of using Next.js with grpc-node

I am currently utilizing gRPC in my project, but I am encountering an issue when trying to initialize the service within a Next.js application. Objective: I aim to create the client service once in the application and utilize it in getServerSideProps (wit ...

Using RxJS switchMap in combination with toArray allows for seamless transformation

I'm encountering an issue with rxjs. I have a function that is supposed to: Take a list of group IDs, such as: of(['1', '2']) Fetch the list of chats for each ID Return a merged list of chats However, when it reaches the toArray ...

Apply CSS styles conditionally to an Angular component

Depending on the variable value, I want to change the style of the p-autocomplete component. A toggle input determines whether the variable is true or false. <div class="switch-inner"> <p [ngClass]="{'businessG': !toggle }" clas ...

Using memoization for React Typescript callback passed as a prop

My component is designed to display data retrieved from a callback provided in the props. To prevent an infinite loop caused by mistakenly passing anonymous functions, I am looking for a method to enforce the usage of memoized callbacks. const DataRenderer ...

Error in custom TypeScript: Incorrect error instance detected within the component

I encountered a unique issue with my custom Error export class CustomError extends Error{ constructor(message: string) { super(message); Object.setPrototypeOf(this, CustomError.prototype); this.name = "CustomError"; } Furthermore ...