html - JavaScript REGEX replacement with the content inside from an external text file -


here code in below comment pattern replaced new content. , it's working fine.

inside html:

<div id="content">     <!-- ### start content ### -->     <p>some text.</p>     <!-- ### end content ### --> </div> 

javascript code:

var str = document.getelementbyid("content").innerhtml;      var txt = str.replace(/<!-- ### start content ### -->([\s\s]*?)<!-- ### end content ### -->/g, '<div id="example">some replaced example stuff !!</div>');     document.getelementbyid("content").innerhtml = txt; 

but, question is.. want replace large block of html code instead of <div id="example">some replaced example stuff !!</div>.

so, this.. plan save large block of html code inside text file , text file called , content inside file displayed when pattern matches.

is possible replace content external text file ?

note: text file placed in root directory itself..

jsfiddle link: http://jsfiddle.net/lipak/2efm1o4c/9/

large block of html code link: http://jsfiddle.net/lipak/zn8fj5q3/

i'd take different approach, doesn't require html comments nor regexp replaces. put name of text file replace contents data attribute on element:

<div id="content" data-replace-file="foo.html"> 

find related elements , replace:

// find elements replaced. var replace = document.queryselectorall('[data-replace-file]');  // loop across elements, replacing each one. (var i=0; i<replace.length; i++) {   var elt = replace[i];   var file = elt.dataset.replacefile;   $(elt).load(file); } 

if insist on plan use html comments, then

var elt = document.getelementbyid("content"); var str = elt.innerhtml; var regexp = /(<!-- ### start content ### -->)([\s\s]*?)(<!-- ### end content ### -->)/;  if (regexp.test(str)) {   $.get("blah.html", function(data) {     elt.innerhtml = str.replace(regexp, "$1" + data + "$3");         }); } 

here entire html file works fine in environment:

<script src="https://code.jquery.com/jquery-2.1.4.js"></script>  <div id="content">     <!-- ### start content ### -->replace me<!-- ### end content ### --> </div>  <button onclick="go()">go</button>  <script>   function go() {     var elt = document.getelementbyid("content");     var str = elt.innerhtml;     var regexp = /(<!-- ### start content ### -->)([\s\s]*?)(<!-- ### end content ### -->)/;      if (regexp.test(str)) {       $.get("blah.html", function(data) {         elt.innerhtml = str.replace(regexp, "$1" + data + "$3");       });     }   } </script> 

Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -