如何循环和替换元素内的字符

时间:2014-09-18 03:36:34

标签: javascript jquery

请您查看This Demo并告诉我如何循环播放<pre>之类的元素并将所有<>替换为一些新字符像:

.replace("<", "1");
.replace(">", "2");

如果我们有<pre>喜欢

<pre>
    < This is a test < which must > replace >
</pre> 

谢谢

2 个答案:

答案 0 :(得分:2)

您可以使用.text()

使用String.replace()RegExp

&#13;
&#13;
$('pre').text(function(i, text){
    return text.replace(/</g, '1').replace(/>/g, '2')
})
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<pre>
    < This is a test < which must > replace >
</pre>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

可能就像

var test = $("pre").text();

var k = test.split("<").join(1).split(">").join(2);

alert(k);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<pre>< This is a test < which must > replace ></pre>

参考:How to replace all occurrences of a string in JavaScript?