I have this string :
const str = 'The world consists of many different colors. for example: red, green, blue.';
I have a dictionary that contains matching words and styles.
const styles = {
RED: 'textRED',
GREEN: 'textGREEN',
BLUE: 'textBLUE',
};
I need to get such an array from 'str':
[
'The world consists of many different colors. for example: ',
<span className={styles['RED']}>red</span>,
", ",
<span className={styles['GREEN']}>green</span>,
", ",
<span className={styles['BLUE']}>blue</span>,
".",
]
Also, letters in words can be of different case, but they should still be replaced by the object.
I'm using nextjs (react) but I don't think it matters much.
CodePudding user response:
If you split
the string, and then use a regular expression to match
the colours, you can map
over the array that match
provides to create an array of span
elements.
Note: you'll have to contain the string in a span too.
function Example({ str, styles }) {
function createJSX(str, styles) {
const [ main, tail ] = str.split(/:\s*/);
const colors = tail.match(/([a-z] )/g);
return [
<span>{main}: </span>,
...colors.map(color => {
const spanStyle = [
'color',
styles[color.toUpperCase()]
].join(' ');
return (
<span
className={spanStyle}
>{color}
</span>
);
})
];
}
return (
<div>
{createJSX(str, styles)}
</div>
);
}
const str = 'The world consists of many different colors. for example: red, green, blue.';
const styles = {
RED: 'textRED',
GREEN: 'textGREEN',
BLUE: 'textBLUE'
};
ReactDOM.render(
<Example str={str} styles={styles} />,
document.getElementById('react')
);
span { margin-left: 0.25em; }
.color:not(:last-child):after { content: ','; color: black; }
.color:last-child:after { content: '.'; color: black; }
.textRED { color: red; }
.textGREEN { color: green; }
.textBLUE { color: blue; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="react"></div>