javascript - 我的“加粗”函数以一种奇怪的方式构建字符串
问题描述
基于我在这里看到的一个函数,我正在尝试构建一个组件,该组件突出显示我将提供的数组中的每个单词,在我给它的字符串中。
例如,如果我像这样使用它:
<Highlight
body="Hi there stack overflow, hope you're all well"
items={["there", "hope"]}
/>
我想回来的是:
嗨,堆栈溢出,希望你一切都好
所以有时它会起作用,有时它不起作用,我无法弄清楚模式。
使用示例字符串,如果我给它这个数组,["there"]
那么我会正确打印它:
嗨,堆栈溢出,希望你一切都好
如果我给它这个数组["there", "hope"]
,那么我会正确打印它:
嗨,堆栈溢出,希望你一切都好
但是如果我给它这个数组["there", "hope", "overflow"]
,那么我会得到这个奇怪的字符串:
嗨,堆栈溢出,hopeoverflowoverflowo verflow,希望你一切都好
这是我目前的功能:
const highlightWords = (source, target, callback) => {
if (!source) return res;
if (!target) return source;
const defaultHighlight = s => <em key={Math.random(1000)}>{s}</em>;
const res = [source];
let lastOffset = 0;
target.forEach(element => {
res.forEach(stringEl => {
console.log(typeof stringEl)
if (typeof stringEl === typeof "")
// Uses replace callback, but not its return value
stringEl.replace(new RegExp(element, "gi"), (val, offset) => {
// Push both the last part of the string, and the new part with the highlight
res.push(
stringEl.substr(lastOffset, offset - lastOffset),
// Replace the string with JSX or anything.
(callback || defaultHighlight)(val)
);
lastOffset = offset + val.length;
});
});
});
// Push the last non-highlighted string
res.push(source.substr(lastOffset));
res.shift();
return res;
};
这是我的组件:
export const Highlight = ({ body, items}) => {
return (
<div>
{highlightWords(body, items, s => (
<span className="bold-700" key={Math.random(1000)}>
{s}
</span>
))}
</div>
);
};
解决方案
推荐阅读
- c# - 通过使用 C# Linq 对多列进行分组来转换层次结构中的数据表
- vulkan - 使用 Vulkan/GPU 转换图像格式?
- ms-access - 循环 DoCmd.SendObject
- mongodb - 具有精简和保存功能的大型猫鼬查询
- kotlin - Kotlin MotionLayout 未按预期扩展
- gradle - 执行“installDist”-Task 时过滤 src/main/dist 中的文件
- c++ - 如何编写 GstSamples 的特定时间间隔(RTP over UDP H264 数据包)?
- react-native - FFmpeg 不适用于名称中包含空格的媒体文件路径
- javascript - useEffect 不会在预期时重新渲染
- windows - 使用 WinUSB 或 HID 驱动程序的 USB 设备原型超时,适用于 libusb