Template variable replacement in written examination


JS regular short, assertions do not match, matching can be captured, capture can be referenced, global all come once.


Given the string containing n variables, it is required to replace the variables with corresponding values, such as $no = 5 and $title =’Jack ‘

<div> <p> {$no}</p> <p> {$title}</p> </div>


  1. Define regular lookup$String variable
  2. Constructing mapping objects between variable keys and variable values
  3. The original replace function is used for regular replacement to avoid looping


str = "<div> <p> {$no}</p> <p> {$title}</p> </div>"
//   one   Creating regular instances
var re = /(?<=\{)($\w+)(?=\})/g
//   two   Building replacement objects
var o = {'no':5, 'title':'jack'}
//   3. Perform replacement
var res = str.replace(re, m => o[m.substr(1)])
//4. Testing


<div> <p> {$no}</p> <p> {$title}</p> </div>
<div> <p> {5}</p> <p> {jack}</p> </div>


Global regularity, using forward and backward assertions, intermediate matching capture.
OriginalreplaceMethod, avoid using too many loops, skillfully use the object key value pair mapping characteristics to achieve value replacement.
In regular brackets, the leading character is a question mark, and the leading character is an assertion, which is used to assist matching. Matching is to help capture, and capture is usually for reference.

This work adoptsCC agreementReprint must indicate the author and the link of this article

Recommended Today

The selector returned by ngrx store createselector performs one-step debugging of fetching logic

Test source code: import { Component } from ‘@angular/core’; import { createSelector } from ‘@ngrx/store’; export interface State { counter1: number; counter2: number; } export const selectCounter1 = (state: State) => state.counter1; export const selectCounter2 = (state: State) => state.counter2; export const selectTotal = createSelector( selectCounter1, selectCounter2, (counter1, counter2) => counter1 + counter2 ); // […]