我想用數組的值替換方括號內的文本。JavaScript替換帶數組的括號之間的文本
例子:
<pre id="text">
[maybe] i should [leave]
[to] help you [see]
[nothing] is [better] [than] this
[and] this is [everything] we need
</pre>
會變成這個樣子
<pre id="text">
[why] i should [go]
[from] help you [run]
[that] is [nothing] [from] this
[now] this is [as] we need
</pre>
請幫助我..謝謝
var arr = ['why', 'go', 'from', 'run', 'that', 'nothing', 'from', 'now', 'as']
var i = 0;
$("#text").each(function() {
$(this).text($(this).text().replace(/\[(.+?)\]/, "["+arr[i]+"]"));
\t i++;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<pre id="text">
[maybe] i should [leave]
[to] help you [see]
[nothing] is [better] [than] this
[and] this is [everything] we need
</pre>
非常感謝你^^ – Spella