I\'m trying to replace parts of a string with JSX tags, like so:
render: function() {
result = this.props.text.replace(\":\",
The accepted answer is two years old. For this problem issue #3368 was created and based on the solution provided by a Facebook employee working on React, react-string-replace was created.
Using react-string-replace, here is how you can solve your problem
const reactStringReplace = require('react-string-replace');
const HighlightNumbers = React.createClass({
render() {
const content = 'Hey my number is 555:555:5555.';
return (
<span>
{reactStringReplace(content, ':', (match, i) => (
<div className="spacer"></div>
))}
</span>
);
},
});
After some research I found that existing libraries doesn't fit my requirements. So, of course, I have written my own:
https://github.com/EfogDev/react-process-string
It is very easy to use. Your case example:
let result = processString({
regex: /:/gim,
fn: () => <div className="spacer"></div>
})(this.props.test);
I had the more common task - wrap all (English) words by custom tag. My solution:
class WrapWords extends React.Component {
render() {
const text = this.props.text;
const isEnglishWord = /\b([-'a-z]+)\b/ig;
const CustomWordTag = 'word';
const byWords = text.split(isEnglishWord);
return (
<div>
{
byWords.map(word => {
if (word.match(isEnglishWord)) {
return <CustomWordTag>{word}</CustomWordTag>;
}
return word;
})
}
</div>
);
}
}
// Render it
ReactDOM.render(
<WrapWords text="Argentina, were playing: England in the quarter-finals (the 1986 World Cup in Mexico). In the 52nd minute the Argentinian captain, Diego Maradona, scored a goal." />,
document.getElementById("react")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="react"></div>
Wrote a utility function for jsx.
const wrapTags = (text: string, regex: RegExp, className?: string) => {
const textArray = text.split(regex);
return textArray.map(str => {
if (regex.test(str)) {
return <span className={className}>{str}</span>;
}
return str;
});
};
If you'd also like to be able to make replacements within replacements (for example, to highlight search terms within urls), check out this node module I created - https://github.com/marcellosachs/react-string-replace-recursively
You guys are using complicated approaches, Just keep it simple:
function replaceJSX(str, find, replace) {
let parts = str.split(find);
for(let i = 0, result = []; i < parts.length; i++) {
result.push(parts[i]);
result.push(replace);
}
return (
<>{result}</>
);
}
replaceJSX(variable, ":", <br />);