1

I have the following script works for the replace with jQuery in innerHTML.

HTML code

<input type="submit" name="replace" id="replace" value="Replace" />

<div class="my_div">Default1 content1</div>
<div class="my_div">Default2 content2</div>

java script

$('#replace').click(function() {
   $('.my_div').html(function( idx, oldHtml){
      return oldHtml.replace(/Default1|content1|Default2|content2/gi, 'symbol1');
   });
});

But I couldn't modify the script for multiple unique replacement. Example I want to replace

Default1 to symbol1

Default2 to symbol2

content1 to symbol3

content2 to symbol4

the following doesn't work

$('#replace').click(function() {
   $('.my_div').html(function( idx, oldHtml){
      return oldHtml.replace(/Default1/gi, 'symbol1');
      return oldHtml.replace(/Default2/gi, 'symbol2');
      return oldHtml.replace(/content1/gi, 'symbol3');
      return oldHtml.replace(/content2/gi, 'symbol4');
   });
});

Also I had early script based on id attribute, which is more than 500 replace lines. Is it possible that I can include similar structure in this new jQuery class attribute?

var str=document.getElementById("my_id").innerHTML;
var n=str.replace("Default1","symbol1");
var n=str.replace("Default2","symbol2");
document.getElementById("my_id").innerHTML=n;
}

Thanks a lot, you guys helped me a lot. :)

1
  • 1
    if you need 500 replace lines there are likely far simpler ways like looping over array, or possibly identifiers in markup that would simplify the whole process. Some better real world examples and markup would help Commented Oct 28, 2012 at 10:06

1 Answer 1

1

Question 1 :

Replace

return oldHtml.replace(/Default1/gi, 'symbol1');
return oldHtml.replace(/Default2/gi, 'symbol2');
return oldHtml.replace(/content1/gi, 'symbol3');
return oldHtml.replace(/content2/gi, 'symbol4');

with

return oldHtml.replace(/Default1/gi, 'symbol1')
    .replace(/Default2/gi, 'symbol2')
    .replace(/content1/gi, 'symbol3')
    .replace(/content2/gi, 'symbol4');

Question 2 :

Replace

var str=document.getElementById("my_id").innerHTML;
var n=str.replace("Default1","symbol1");
var n=str.replace("Default2","symbol2");
document.getElementById("my_id").innerHTML=n;

with

var $div = $('#my_id');
$div.html(
    $div.html().replace("Default1","symbol1")
    .replace("Default2","symbol2")
);

(if you use jQuery, no need for those getElementById)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.