-
Notifications
You must be signed in to change notification settings - Fork 264
Open
Description
const input = 'plain text #{special} more text';
const expectedOutput = [
{originText: 'plain text ', isSpecialText: false},
{originText: 'special', isSpecialText: true},
{originText: ' more text', isSpecialText: false}
];
expect(text2Array(input)).toEqual(expectedOutput);参考答案
双指针
function text2Array(input) {
const result = [];
const n = input.length;
let i = 0; // 当前扫描指针
let bufferStart = 0; // 普通文本起点
while (i < n) {
// 发现 #{ 起始标记
if (input[i] === '#' && input[i + 1] === '{') {
// 先结算前面的普通文本
if (i > bufferStart) {
result.push({
originText: input.slice(bufferStart, i),
isSpecialText: false
});
}
// 跳过 #{
i += 2;
const specialStart = i;
// 找到 }
while (i < n && input[i] !== '}') {
i++;
}
// 如果找到了 },提取 special
if (i < n) {
result.push({
originText: input.slice(specialStart, i),
isSpecialText: true
});
i++; // 跳过 }
bufferStart = i;
} else {
// 没找到 },说明不合法,剩余当普通文本
break;
}
} else {
i++;
}
}
// 处理剩余普通文本
if (bufferStart < n) {
result.push({
originText: input.slice(bufferStart),
isSpecialText: false
});
}
return result;
}正则
function text2Array(input) {
const result = [];
const regex = /#\{([^}]+)\}/g;
let lastIndex = 0;
let match;
while ((match = regex.exec(input)) !== null) {
const { index } = match;
// 普通文本
if (index > lastIndex) {
result.push({
originText: input.slice(lastIndex, index),
isSpecialText: false
});
}
// 特殊文本(去掉 #{ })
result.push({
originText: match[1],
isSpecialText: true
});
lastIndex = regex.lastIndex;
}
// 处理尾部普通文本
if (lastIndex < input.length) {
result.push({
originText: input.slice(lastIndex),
isSpecialText: false
});
}
return result;
}Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
No labels