如何在javascript中替换两个陈述的字符串之间的字符串

时间:2016-03-10 15:53:41

标签: javascript replace replaceall

我想将一些代码替换为dom元素。例如:

[emo]sad[emo] or [emo]sad[/emo]

<span class='smiley medium' data-emo='" + emo + "'></span>

<span class='smiley medium' data-emo='sad'></span>

有可能吗?

1 个答案:

答案 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
/;

jsbin:https://jsbin.com/nofizosebe/1/edit?js,console