首页 > 解决方案 > 我的“加粗”函数以一种奇怪的方式构建字符串

问题描述

基于我在这里看到的一个函数,我正在尝试构建一个组件,该组件突出显示我将提供的数组中的每个单词,在我给它的字符串中。

例如,如果我像这样使用它:

  <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>
  );
};

标签: javascriptreactjs

解决方案


推荐阅读