我想将一些代码替换为dom元素。例如:
[emo]sad[emo] or [emo]sad[/emo]
至
<span class='smiley medium' data-emo='" + emo + "'></span>
喜欢
<span class='smiley medium' data-emo='sad'></span>
可能吗?
最佳答案
怎么样:
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
分解reg ex:
var regex = /
^ // start
\[(\w+)\] // the first [] block, match inside the []
(.+) // match between the [] blocks
\[\/?(\w+)\] // the second [] block, optional "/", match inside the []
$ // end
/;
jsbin:https://jsbin.com/nofizosebe/1/edit?js,console
关于javascript - 如何在JavaScript中的两个指定字符之间替换字符串,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35921260/