我有两根弦
\r\n
def\n
de我需要在字符串 1 中找到字符串 2 的索引。
我显然不能使用indexOf(),所以我需要一些可以像它一样工作的东西,但考虑到不同的行结尾。
我无法修改原始字符串,因为我需要原始字符串中的子字符串索引。如果我用
\r\n
替换所有 \n
,它会弄乱原始索引,所以我必须以某种方式恢复它们。
(FWIW,这个问题没有任何 TypeScript 特定的内容。只是 JavaScript。)
您可以通过使用交替
\r\n|\r|\n
将您要查找的字符串转换为正则表达式来做到这一点,并且确保转义中间的部分(请参阅这个问题的答案)那个)。
TypeScript 类型注释被注释掉的示例:
// From https://stackoverflow.com/a/3561711/157247
function escapeRegex(string) {
return string.replace(/[/\-\\^$*+?.()|[\]{}]/g, '\\$&');
}
function test(str/*: string */, substr/*: string*/) {
// Split up the text on any of the newline sequences,
// then escape the parts in-between,
// then join together with the alternation
const rexText = substr
.split(/\r\n|\n|\r/)
.map((part) => escapeRegex(part))
.join("\\r\\n|\\n|\\r");
// Create the regex
const re = new RegExp(rexText);
// Run it
const match = re.exec(str);
if (match) {
console.log(`Found ${JSON.stringify(match[0])} at index ${match.index} in ${JSON.stringify(str)}`);
} else {
console.log(`Not found`);
}
}
test("abc\r\ndef", "c\nde");