javascript - 如何使用格式化进行字符串替换
问题描述
在我的 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)
但我试图想办法格式化变量文本(例如粗体格式),所以文本出来是这样的:
这是苹果,这是香蕉,这是梨。
我怎样才能做到这一点?
解决方案
您可以将每个替换包装在 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" />
推荐阅读
- mysql - 用sql查询获取工资最低的员工姓名
- generator - 无法映射时间戳类型--mybatis 生成器
- android - 在 ViewStub Android 中查找控件
- css - 当我点击播放时,如何在网站上膨胀嵌入的 youtube 视频帧?
- pyspark - How do I select columns from a Spark dataframe when I also need to use withColumnRenamed?
- c# - Azure 逻辑应用接收图像 HTTP 触发器
- c# - MSI 安装程序选项 - 卸载应用程序
- c# - 集合未过滤 WPF 中的列表项
- matlab - Matlab中输入的确定是真实的
- sql - 提高 SQL 查询的性能