我有一个查找和替换脚本,当单词没有任何特殊字符时,该脚本没有问题。但是,很多时候 是特殊字符,因为它会查找名称。到目前为止,这正在破坏脚本。
脚本查找{<some-text>}
并尝试替换内容(以及删除括号)。
示例:
text.rtf
Here's a name with special char {Kotouč}
script.ts
import * as fs from "fs";
// Ingest the rtf file.
const content: string = fs.readFileSync("./text.rtf","utf8");
console.log("content::\n",content);
// The string we are looking to match in file text.
const plainText: string = "{Kotouč}";
// Look for all text that matches the patter `{TEXT_HERE}`.
const anyMatchPattern: RegExp = /{(.*?)}/gi;
const matches: string[] = content.match(anyMatchPattern) || [];
const matchesLen: number = matches.length;
for (let i: number = 0; i < matchesLen; i++) {
// It correctly identifies the targeted text.
const currMatch: string = matches[i];
const isRtfMetadata: boolean = currMatch.endsWith(";}");
if (isRtfMetadata) {
continue;
}
// Here I need a way to escape `plainText` string so that it matches the source.
console.log("currMatch::",currMatch);
console.log("currMatch === plainText::",currMatch === plainText);
if (currMatch === plainText) {
const newContent: string = content.replace(currMatch,"IT_WORKS!");
console.log("newContent:",newContent);
}
}
输出
content::
{\rtf1\ansi\ansicpg1252\cocoartf1671\cocoasubrtf600
{\fonttbl\f0\fswiss\fcharset0 Helvetica;}
{\colortbl;\red255\green255\blue255;}
{\*\expandedcolortbl;;}
\margl1440\margr1440\vieww10800\viewh8400\viewkind0
\pard\tx720\tx1440\tx2160\tx2880\tx3600\tx4320\tx5040\tx5760\tx6480\tx7200\tx7920\tx8640\pardirnatural\partightenfactor0
\f0\fs24 \cf0 Here's a name with special char \{Kotou\uc0\u269 \}.}
currMatch:: {Kotou\uc0\u269 \}
currMatch === plainText:: false
它看起来像是ANSI的转义符,我尝试使用jsesc,但是会生成一个不同的字符串{Kotou\u010D}
,而不是文档生成的{Kotou\uc0\u269 \}
。
如何动态地对plainText
字符串变量进行转义,使其与文档中的内容匹配?