0

Can you please take a look at This Demo and let me know how I can loop through and element like <pre> and replace all < and > with some new characters like:

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

if we have a <pre> like

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

Thanks

user3649067
  • 227
  • 3
  • 7
  • 16

2 Answers2

2

You can use .text() and String.replace() using an RegExp

$('pre').text(function(i, text){
    return text.replace(/</g, '1').replace(/>/g, '2')
})
<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>
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
0

may be like

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>

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

Community
  • 1
  • 1
Mithun Satheesh
  • 27,240
  • 14
  • 77
  • 101