首页 > 解决方案 > 如何使用格式化进行字符串替换

问题描述

在我的 React 应用程序中,我使用 string.replace 将字符串的一部分替换为变量,并使用%VARIABLE%语法识别变量。对于纯文本,它可以正常工作:

const text = 'This is %FIRST%, this is %SECOND%, and this is %THIRD%.'
  .replace(/%\w+%/g, ((variable) => ({
    '%THIRD%': 'a pear',
    '%FIRST%': 'an apple',
    '%SECOND%': 'a banana',
  }[variable] || variable)));
console.log(text)

但我试图想办法格式化变量文本(例如粗体格式),所以文本出来是这样的:

这是苹果,这是香蕉,这是

我怎样才能做到这一点?

标签: javascriptreactjs

解决方案


您可以将每个替换包装在 a 中span并应用特定的 CSS 类和规则。使用dangerouslySetInnerHTML将 html 字符串呈现为 div/元素。

const text = 'This is %FIRST%, this is %SECOND%, and this is %THIRD%.'
  .replace(/%\w+%/g, ((variable) => {
    const value = {
      '%THIRD%': 'a pear',
      '%FIRST%': 'an apple',
      '%SECOND%': 'a banana',
    }[variable] || variable;
    
    return `<span class="bold">${value}</span>`;
  }));
  
console.log(text);

const rootElement = document.getElementById("root");
ReactDOM.render(
  <div dangerouslySetInnerHTML={{ __html: text }} />,
  rootElement
);
.bold {
  font-weight: bold;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.1/umd/react-dom.production.min.js"></script>
<div id="root" />


推荐阅读