我需要替换粗体文本 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/