javascript - 加粗文本中的特定单词 - React Native?

标签 javascript reactjs react-native

我需要替换粗体文本 based on the index value代替{index}这个词应该是粗体

示例:

 {
  sentence: {0} and {1} are great
  boldText: ['You', 'Your Family']
 }

输出:

你的家人都很棒。

最佳答案

这是一个简单的例子。

希望对您有所帮助!

const sample = {
  sentence: '{0} and {1} are great',
  boldText: ['You', 'Your Family']
};

const applyBoldStyle = text => text.sentence.replace(/\{(\d+)\}/g, (match, i) => `<b>${text.boldText[i]}</b>`);

console.log(applyBoldStyle(sample));

请注意,您可以传递任何您想要适合 react-native 或其他内容的内容。在这里,我通过 <b> 传递简单的 HTML标签,这里重要的是 replace功能。让它返回任何你想要的。

对于 react-native,您可能希望使用以下内容:

const sample = {
  sentence: '{0} and {1} are great',
  boldText: ['You', 'Your Family']
};

const applyBoldStyle = text => {
  let numberOfItemsAdded = 0;
  const result = text.sentence.split(/\{\d+\}/);
  text.boldText.forEach((boldText, i) => result.splice(++numberOfItemsAdded + i, 0, <Text style={{fontWeight: 'bold'}}>{boldText}</Text>););
  return <Text>{result}</Text>;
};

关于javascript - 加粗文本中的特定单词 - React Native?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51423251/

相关文章:

javascript - 按照教程时 react 错误

javascript - 为什么在 makeSquare(){...} 之前添加关键字函数会给我解析错误

windows - 如何使用 VirtualBox 和 Ubuntu 作为开发环境以及 Windows 10 和 Android Studio 作为 Android 模拟器在 React Native 中进行开发

reactjs - 如何在 react-bootstrap 自定义上自定义选项卡

react-native - 从嵌套导航器中隐藏父级的导航标题

reactjs - Eslint-config-rallycoding 安装

javascript - 这是 Xpath 评估中的 Chrome 错误吗

javascript - 搜索匹配变量的字符串键数组并使用 javascript/jquery 返回所有值

javascript - 通过 Node.js 将文档插入 MongoDB 时出错

javascript - 如何将 AngularJS 2 连接到 REST-API?