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

Navigating through JSON object using Angular 2's ngFor iterator

I want to test the front end with some dummy JSON before I write a service to get real JSON data. What is the correct way to iterate through JSON using ngFor? In my component.ts file (ngOnInit()), I tried the following code with a simple interface: var js ...

Tips for aligning the types of objects transmitted from a Web API backend to a React/Redux frontend

After creating a backend for my app using .net, I now have CRUD operations available to me. When performing a POST action, the response includes an entire new item object: {"Id":"7575c661-a40b-4161-b535-bd332edccc71","Text":"as","CreatedAt":"2018-09-13T15 ...

Experiencing a console error which reads: "SyntaxError: Missing ) after argument list."

While working on configuring a new React CSR app and incorporating some boilerplate libraries, I encountered an error in the console: Uncaught SyntaxError: missing ) after argument list (at @emotion_react_macro.js?v=30f6ea37:29894:134) I am hesitant to ma ...

Achieving Jest integration with Angular 9 in a Storybook setup

We are currently utilizing Storybook 5 alongside Angular 9, with Jest 26 for some of the testing procedures. The issue we're facing arises when using Typescript version below 3.8.0 - a requirement for Angular 9's ng build --prod. This results in ...

Having trouble setting State in React with Typescript?

I have encountered an issue with merging strings in an array. Despite successfully joining two strings and logging the result using console.log('Dates: ' + mergedActions), the merged string doesn't seem to be set in this.state.MergedAllActio ...

Can you explain the distinction between Reflect.getMetadata and Reflect.getOwnMetadata?

Just like the title says, the reflect-metadata API comes with a method called getMetadata and another called getOwnMetadata. Can you explain the distinction between them? The same question applies to hasOwnMetadata, and so on. ...

What is the best way to delay an observable from triggering the next event?

In my Angular project, I am implementing RxJs with two subjects. s1.next() s1.subscribe(() => { // perform some operation and then trigger the event for s2 s2.next() }); s2.subscribe(() => { // perform some operat ...

The parameter type 'Object' cannot be assigned to the parameter type 'string'

Everything seems to be working fine in my application, but I am encountering the following error message: The argument of type 'Object' is causing an issue and cannot be assigned to a parameter of type 'string' Here is the code snip ...

What is the comparable alternative to promise<void> in observables?

I've been working with Angular using TypeScript and I'm attempting to return a promise from an observable. What is the correct way to accomplish this? So far, I have tried the following: of(EMPTY).toPromise() // error: Promise<Observable<n ...

Unable to compile TypeScript files using gulp while targeting ES5

After starting my first Angular2 app, I encountered an issue where I couldn't use gulp to compile for es5. Below is the dependencies file: "dependencies": { "@angular/common": "2.0.0", "@angular/compiler": "2.0.0", "@angular/compiler-cli ...

Converting a string to a number in an Angular template

Within my select box, I am capturing the selected value and binding it to the variable startingYear. However, I need the type of startingYear to be a number, but it is currently registering as a string. Is there a way to convert it to a number? console ...

The element in the iterator in next.js typescript is lacking a necessary "key" prop

Welcome to my portfolio web application! I have created various components, but I am facing an issue when running 'npm run build'. The error message indicates that a "key" prop is missing for an element in the iterator. I tried adding it, but the ...

Having trouble with the "Vs Code nx console generate" command? It seems that there are no flags available to configure

My issue involves the nx console extension installed in my Visual Studio Code. Every time I attempt to use the generate command for components, services, or libraries, I receive an error message stating "ng generate @schematics/angular:component This com ...

Best method for integrating widget scripts in Angular 5

I am in the process of developing an Angular 5 application and I have encountered a challenge while trying to integrate a widget into one of the components. Following the guidance provided in this particular question, I attempted to add the widget as inst ...

Mocha has difficulty compiling Typescript code on Windows operating system

In developing my nodejs module, I created several unit tests using Mocha and Chai. While these tests run smoothly on macOS, they encounter compilation issues on Windows, resulting in the following error: D:\projects\antlr4-graps>npm test > ...

Transferring data from the server to the client side in Next JS with the help of getInitialProps

I am currently developing an application using nextJS. Within server/index.ts, I have the following code: expressApp.get('/', (req: express.Request, res: express.Response) => { const parsedUrl = parse(req.url, true); const { query } = ...

Guide to integrating a native web component into Vue3

After creating the renderComponent method to display a webcomponent, I attempted to use it in my componentView.vue file. export function renderComponent(el: Element, component: Component,props: VNodeProps,appContext: AppContext){ let vnode: VNode | undefin ...

Deactivate multiple textareas within a loop by utilizing JQuery/Typescript and KnockoutJS

I am working on a for loop that generates a series of textareas with unique ids using KO data-binding, but they all share the same name. My goal is to utilize Jquery to determine if all the textareas in the list are empty. If they are, I want to disable al ...

Generics in Typescript interfaces

I'm trying to grasp the meaning of T = {} within this TypeScript interface. I've searched for documentation on this usage but haven't found anything specific. How does it differ from simply using T? interface CustomProps<T = {}> { ...