React
HTML
<div id="app"></div>
React
class TodoApp extends React.Component {
constructor(props) {
super(props);
this.asdf();
}
asdf() {
var table = {
"*":{
"begin":"<strong>",
"end":"</strong>"
},
"_":{
"begin":"<em>",
"end":"</em>"
},
"!":{
"begin":"<MyComponent onClick={this.action}>",
"end":"</MyComponent>"
},
};
var myMarkdown = "hello *asdf* *how* _are_ you !doing! today";
var tagFinder = /(?<item>(?<tag_begin>[*|!|_])(?<content>\w+)(?<tag_end>\k<tag_begin>))/gm;
//Use case 1: direct string replacement
var replaced = myMarkdown.replace(tagFinder, replacer);
function replacer(match, whole, tag_begin, content, tag_end, offset, string) {
return table[tag_begin]["begin"] + content + table[tag_begin]["end"];
}
//Use case 2: React components
var pieces = [];
var lastMatchedPosition = 0;
myMarkdown.replace(tagFinder, breaker);
function breaker(match, whole, tag_begin, content, tag_end, offset, string) {
var piece;
if (lastMatchedPosition < offset)
{
piece = string.substring(lastMatchedPosition, offset);
pieces.push("\"" + piece + "\"");
}
piece = table[tag_begin]["begin"] + content + table[tag_begin]["end"];
pieces.push(piece);
lastMatchedPosition = offset + match.length;
}
console.log(pieces);
}
render() {
return (
<div></div>
)
}
}
ReactDOM.render(<TodoApp />, document.querySelector("#app"))