我想将一些代码替换为dom元素。例如:
[emo]sad[emo] or [emo]sad[/emo]
到
<span class='smiley medium' data-emo='" + emo + "'></span>
像
<span class='smiley medium' data-emo='sad'></span>
有可能吗?
答案 0 :(得分:2)
怎么样:
var s1 = "[emo]sad[emo]";
var s2 = "[emo]sad[/emo]";
var regex = /^\[(\w+)\](.+)\[\/?(\w+)\]$/; // matches s1 and s2
var replacement = "<span class='smiley medium' data-$1='$2'></span>";
var s1HTML = s1.replace(regex,replacement);
var s2HTML = s2.replace(regex,replacement);
// now append s1HTML and s2HTML to dom
分解注册:
var regex = /
^ // start
\[(\w+)\] // the first [] block, match inside the []
(.+) // match between the [] blocks
\[\/?(\w+)\] // the second [] block, optional "/", match inside the []
$ // end
/;