user3649067
user3649067

Reputation: 237

How to Loop and Replace Characters inside an Element

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

Upvotes: 0

Views: 42

Answers (2)

Mithun Satheesh
Mithun Satheesh

Reputation: 27845

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?

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388316

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>

Upvotes: 2

Related Questions