JavaScript: Replace placeholders with HTML tags from array

In the example below, click "Remove Tags"

I want the tags to be added back in from the array when "Add Tags" is clicked.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Title</title>
</head>
<body>

<div id="content">
<h1 class="h">Heading</h1>
<p>Hello <strong class="w">World</strong>.</p>
<p><span style="color: red">red</span> <span style="color: blue">blue</span>  <span style="color: green">green</span></p>
</div>

<script type="text/javascript">
/*<![CDATA[*/

// Thanks, hielo
// Thanks, senthurpandian

var tagsOpen;
var tagsClose;

var obj=document.getElementById('content');
if(obj){
	var myInnerHTML = "";
	var tagsOpen=obj.innerHTML.match(/(<[a-zA-Z]+[^>]*?>)/g);
	var tagsClose=obj.innerHTML.match(/(<\/[a-zA-Z]+[^>]*?>)/g);
}

function tagsRemove () {
	var obj=document.getElementById('content');
	if(obj){
	obj.innerHTML = obj.innerHTML.replace(/(<\/[a-zA-Z]+[^>]*?>)/g, " =** ");
	obj.innerHTML = obj.innerHTML.replace(/(<[a-zA-Z]+[^>]*?>)/g, " **= ");
	}
}

function tagsAdd(){
	var obj=document.getElementById('content');
	if(obj){
	alert("I want to add all the HTML tags back from the arrays tagsOpen and tagsClose");

	alert('Closing Tags: \n\n'+tagsClose.join("\n"))
	alert('Opening Tags: \n\n'+tagsOpen.join("\n"))

	}
}


/*]]>*/
</script>

<input type="button" value="Remove Tags" onclick="tagsRemove()" />
<input type="button" value="Add Tags" onclick="tagsAdd()" />

</body>
</html>

Open in new window

LVL 16
hankknightAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

StealthyDevCommented:
Why dont you have the previous HTML in a temporary variable? Like below?


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Title</title>
</head>
<body>

<div id="content">
<h1 class="h">Heading</h1>
<p>Hello <strong class="w">World</strong>.</p>
<p><span style="color: red">red</span> <span style="color: blue">blue</span>  <span style="color: green">green</span></p>
</div>

<script type="text/javascript">
/*<![CDATA[*/

// Thanks, hielo
// Thanks, senthurpandian

var tagsOpen;
var tagsClose;
var myContents = "";

var obj=document.getElementById('content');
if(obj){
        var myInnerHTML = "";
        var tagsOpen=obj.innerHTML.match(/(<[a-zA-Z]+[^>]*?>)/g);
        var tagsClose=obj.innerHTML.match(/(<\/[a-zA-Z]+[^>]*?>)/g);
}

function tagsRemove () {
        var obj=document.getElementById('content');
        if(obj){
		myContents = obj.innerHTML;
        obj.innerHTML = obj.innerHTML.replace(/(<\/[a-zA-Z]+[^>]*?>)/g, " =** ");
        obj.innerHTML = obj.innerHTML.replace(/(<[a-zA-Z]+[^>]*?>)/g, " **= ");
        }
}

function tagsAdd(){
        var obj=document.getElementById('content');
        if(obj){
        /*alert("I want to add all the HTML tags back from the arrays tagsOpen and tagsClose");

        alert('Closing Tags: \n\n'+tagsClose.join("\n"))
        alert('Opening Tags: \n\n'+tagsOpen.join("\n"))*/
		obj.innerHTML = myContents;
        }
}


/*]]>*/
</script>

<input type="button" value="Remove Tags" onclick="tagsRemove()" />
<input type="button" value="Add Tags" onclick="tagsAdd()" />

</body>
</html>

Open in new window

0
hankknightAuthor Commented:
senthurpandian, thanks for the idea, but that will not do what I need it to.  

The content will actually be translated to a different language before the tags are added back.
http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/Q_25977689.html

Please test the code below:
<html>
  <head>
    <script type="text/javascript" src="http://www.google.com/jsapi">
    </script>
    <script type="text/javascript">
    google.load("language", "1");
    function initialize() {
      var text = document.getElementById("content").innerHTML;

	var tagsOpen=text.match(/(<[a-zA-Z]+[^>]*?>)/g);
	var tagsClose=text.match(/(<\/[a-zA-Z]+[^>]*?>)/g);
	text = text.replace(/(<\/[a-zA-Z]+[^>]*?>)/g, " =** ");
	text = text.replace(/(<[a-zA-Z]+[^>]*?>)/g, " **= ");

      google.language.detect(text, function(result) {
        if (!result.error && result.language) {
          google.language.translate(text, result.language, "es",
                                    function(result) {
            var translated = document.getElementById("translation");
            if (result.translation) {
              translated.innerHTML = result.translation;
            }
          });
        }
      });
    }
    google.setOnLoadCallback(initialize);
    </script>
</head>
<body>

<div id="content">
<h1 class="h">Heading</h1>
<p>Hello <strong class="w">World</strong>.</p>
<p><span style="color: red">red</span> <span style="color: blue">blue</span>  <span style="color: green">green</span></p>
</div>

<textarea style="width: 90%; height: 333px;" id="translation"></textarea>

<p><input type="button" value="Add Tags" onclick="tagsAdd()" /></p>

</body>
</html>

Open in new window

0
Michel PlungjanIT ExpertCommented:
This does not work well for some reason.


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Title</title>
</head>
<body>

<div id="content">
<h1 class="h">Heading</h1>
<p>Hello <strong class="w">World</strong>.</p>
<p><span style="color: red">red</span> <span style="color: blue">blue</span>  <span style="color: green">green</span></p>
</div>

<script type="text/javascript">
/*<![CDATA[*/

// Thanks, hielo
// Thanks, senthurpandian

var tagsOpen;
var tagsClose;

var obj=document.getElementById('content');
if(obj){
	var myInnerHTML = "";
	var tagsOpen=obj.innerHTML.match(/(<[a-zA-Z]+[^>]*?>)/g);
	var tagsClose=obj.innerHTML.match(/(<\/[a-zA-Z]+[^>]*?>)/g);
}

function tagsRemove () {
	var obj=document.getElementById('content');
	if(obj){
	obj.innerHTML = obj.innerHTML.replace(/(<\/[a-zA-Z]+[^>]*?>)/g, " =** ");
	obj.innerHTML = obj.innerHTML.replace(/(<[a-zA-Z]+[^>]*?>)/g, " **= ");
	}
}

function tagsAdd(){
	var obj=document.getElementById('content');
	if(obj){
//	  alert("I want to add all the HTML tags back from the arrays tagsOpen and tagsClose");

//  	alert('Closing Tags: \n\n'+tagsClose.join("\n"))
//  	alert('Opening Tags: \n\n'+tagsOpen.join("\n"))
    var text = obj.innerHTML;
    alert(text)
    for (var i=0;i<tagsOpen.length;i++) {
      text = text.replace(" =** ",tagsOpen[i])
    }
    for (var i=0;i<tagsClose.length;i++) {
      text = text.replace(" **= ",tagsClose[i])
    }
    alert(text)
    obj.innerHTML=text;
	}
}


/*]]>*/
</script>

<input type="button" value="Remove Tags" onclick="tagsRemove()" />
<input type="button" value="Add Tags" onclick="tagsAdd()" />

</body>
</html>

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

hankknightAuthor Commented:
I modified mplungjan's code and it works better but it still doesn't work perfectly.

The last tag gets messed up!
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>Title</title>
    </head>
    
    <body>
        <div id="content">
            <h1 class="h">
                Heading
            </h1>
            <p>
                Hello
                <strong class="w">
                    World
                </strong>
                .
            </p>
            <p>
                <span style="color: red">
                    red
                </span>
                <span style="color: blue">
                    blue
                </span>
                <span style="color: green">
                    green
                </span>
            </p>
        </div>
        <script type="text/javascript">
            /*<![CDATA[*/

            // Thanks, hielo
            // Thanks, senthurpandian
            // Thanks, mplungjan

            var tagsOpen;
            var tagsClose;

            var obj = document.getElementById('content');
            if (obj) {

                var tagsOpen = obj.innerHTML.match(/(<[a-zA-Z]+[^>]*?>)/g);
                var tagsClose = obj.innerHTML.match(/(<\/[a-zA-Z]+[^>]*?>)/g);
            }

            function tagsRemove() {
                var obj = document.getElementById('content');
                if (obj) {
                    obj.innerHTML = obj.innerHTML.replace(/(<\/[a-zA-Z]+[^>]*?>)/g, " =** ");
                    obj.innerHTML = obj.innerHTML.replace(/(<[a-zA-Z]+[^>]*?>)/g, " **= ");
                }
            }

            function tagsAdd() {
                var obj = document.getElementById('content');
                if (obj) {
                    var text = obj.innerHTML;

                    for (var i = 0; i < tagsClose.length; i++) {
                        text = text.replace(" =** ", tagsClose[i])
                    }

                    for (var i = 0; i < tagsOpen.length; i++) {
                        text = text.replace(" **= ", tagsOpen[i])
                    }
                    obj.innerHTML = text;
                }
            }


            /*]]>*/
        </script>
        <input type="button" value="Remove Tags" onclick="tagsRemove()" />
        <input type="button" value="Add Tags" onclick="tagsAdd()" />
    </body>
</html>

Open in new window

0
Michel PlungjanIT ExpertCommented:
What did you change?
0
hankknightAuthor Commented:
I changed the order for doing the replace so that the closing tags were added first:

    for (var i=0;i<tagsClose.length;i++) {
      text = text.replace(" **= ",tagsClose[i])
    }

    for (var i=0;i<tagsOpen.length;i++) {
      text = text.replace(" =** ",tagsOpen[i])
    }

0
StealthyDevCommented:
Hi again!

Actually the logic they have used is perfect. But the delimiter we have selected is wrong.

Please find below, I have declared delimeters for openning and closing tags.
Please check and revert.

Best Regards.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>Title</title>
    </head>
    
    <body>
        <div id="content">
            <h1 class="h">
                Heading
            </h1>
            <p>
                Hello
                <strong class="w">
                    World
                </strong>
                .
            </p>
            <p>
                <span style="color: red">
                    red
                </span>
                <span style="color: blue">
                    blue
                </span>
                <span style="color: green">
                    green
                </span>
            </p>
        </div>
        <script type="text/javascript">
            /*<![CDATA[*/

            // Thanks, hielo
            // Thanks, senthurpandian
            // Thanks, mplungjan

            var tagsOpen;
            var tagsClose;
			var openTagDelim = "%^$%%($";
			var closeTagDelim = "#^%^$%*$";

            var obj = document.getElementById('content');
            if (obj) {

                var tagsOpen = obj.innerHTML.match(/(<[a-zA-Z]+[^>]*?>)/g);
                var tagsClose = obj.innerHTML.match(/(<\/[a-zA-Z]+[^>]*?>)/g);
            }

            function tagsRemove() {
                var obj = document.getElementById('content');
                if (obj) {
                    obj.innerHTML = obj.innerHTML.replace(/(<\/[a-zA-Z]+[^>]*?>)/g, closeTagDelim);
                    obj.innerHTML = obj.innerHTML.replace(/(<[a-zA-Z]+[^>]*?>)/g, openTagDelim);
                }
            }

            function tagsAdd() {
                var obj = document.getElementById('content');
                if (obj) {
                    var text = obj.innerHTML;

                    for (var i = 0; i < tagsClose.length; i++) {
                        text = text.replace(closeTagDelim, tagsClose[i])
                    }

                    for (var i = 0; i < tagsOpen.length; i++) {
                        text = text.replace(openTagDelim, tagsOpen[i])
                    }
                    obj.innerHTML = text;
                }
            }


            /*]]>*/
        </script>
        <input type="button" value="Remove Tags" onclick="tagsRemove()" />
        <input type="button" value="Add Tags" onclick="tagsAdd()" />
    </body>
</html>

Open in new window

0
Michel PlungjanIT ExpertCommented:
How come many technical people of Indian origin use the word "revert" instead of "respond" or "get back to me on this" ?
0
StealthyDevCommented:
@mplungjan: thanks for your valuable comment. I'll try to correct this.

:)
0
Michel PlungjanIT ExpertCommented:
It was not a criticism - just a question. Seems it is an Indian English construct like "Is it?" meaning "really?" is South African. Apologies for the interruption, the scheduled programme will resume shortly
0
hankknightAuthor Commented:
senthurpandian, thanks for your idea but your code is not an improvement.   Please test it in Firefox or Chrome and see how the colours are incorrectly associated with the words.   You code changes "red" to blue and blue to green.  Your code works with Internet Explorer but not other browsers.

Please revert the code and try again.  :-)

Michel, your comprehension of the English language is incredible.  I spent my childhood years in Africa.  Were you able to detect that from my selection of words?

I don't understand why none of the ideas presented work.  The problem is probably caused by a simple mathematical mistake.
0
Michel PlungjanIT ExpertCommented:
Thanks for the kind words. No I have not noticed any ideosyncrasies (hmm where is the spell checker on that word) in your written language. As for the issue at hand, I need to get to a pc to comment and test
0
hankknightAuthor Commented:
After eating lunch, I was able to figure it out.  It is amazing what a bit of food can do!
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>Title</title>
    </head>
    <body>
        <div id="content">
            <h1 class="h">Heading</h1>
            <p>Hello<strong class="w">World</strong>.</p>
            <p>
                <span style="color: red">red</span>
                <span style="color: blue">blue</span>
                <span style="color: green">green</span>
            </p>
            <h1 class="h">This is the footer</h1>
        </div>

<p>
        <input id="tagsRemove" type="button" value="Remove Tags" onclick="tagsRemove()" />
        <input id="tagsAdd" type="button" value="Add Tags" onclick="tagsAdd()" style="display: none;" />
</p>

        <script type="text/javascript">
            /*<![CDATA[*/
            var tagsOpen;
            var tagsClose;

            var obj = document.getElementById('content');
            if (obj) {
                var tagsOpen = obj.innerHTML.match(/(<[^\/>][^>]*?>)/g);
                var tagsClose = obj.innerHTML.match(/(<\/+[^>]*?>)/g);
            }

            function tagsRemove () {
                var obj = document.getElementById('content');
                if (obj) {
                    var c = obj.innerHTML.replace(/(<\/+[^>]*?>)/g, '\u2194');
                    var c = c.replace(/(<[^\/>][^>]*?>)/g, '\u2192');
                    obj.innerHTML = c;
                }
	    document.getElementById('tagsRemove').style.display='none';
	    document.getElementById('tagsAdd').style.display='inline';
            }

            function tagsAdd () {

                var obj = document.getElementById('content');
                if (obj) {
                    var text = '';
                    var chunk = Array();
                    chunk = obj.innerHTML.split('\u2192');
                    for (var i = 0; i < chunk.length; i++) {
                       if(tagsOpen[i]) text = text + chunk[i] + tagsOpen[i];
                       else if(chunk[i]) text = text + chunk[i];
                     }

                    var chunk = Array();
                    chunk = text.split('\u2194');
                    text='';
                    for (var i = 0; i < chunk.length; i++) {
                     if(tagsClose[i])  text = text + chunk[i] + tagsClose[i];
                    }
                     obj.innerHTML = text;
                }
	    document.getElementById('tagsAdd').style.display='none';
	    document.getElementById('tagsRemove').style.display='inline';
            }
	document.getElementById('tagsAdd').style.display='none';
            /*]]>*/
        </script>

</body>
</html>

Open in new window

0
Michel PlungjanIT ExpertCommented:
So what was it exactly? I was debugging like this and could not figure out the issue or the tons of <s I got

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>Title</title>
    </head>
    
    <body>
        <div id="content">
            <h1 class="h">
                Heading
            </h1>
            <p>
                Hello
                <strong class="w">
                    World
                </strong>
                .
            </p>
            <p>
                <span style="color: red">
                    red
                </span>
                <span style="color: blue">
                    blue
                </span>
                <span style="color: green">
                    green
                </span>
            </p>
        </div>
        <div id=msg></div>
        <script type="text/javascript">
            /*<![CDATA[*/

            // Thanks, hielo
            // Thanks, senthurpandian
            // Thanks, mplungjan

            var tagsOpen;
            var tagsClose;

            var obj = document.getElementById('content');
            if (obj) {

                var tagsOpen = obj.innerHTML.match(/(<[a-zA-Z]+[^>]*?>)/g);
show(tagsOpen.join('\n'));                
                var tagsClose = obj.innerHTML.match(/(<\/[a-zA-Z]+[^>]*?>)/g);
show(tagsClose.join('\n'));            }

            function tagsRemove() {
                var obj = document.getElementById('content');
                if (obj) {
show(obj.innerHTML)
                    obj.innerHTML = obj.innerHTML.replace(/(<\/[a-zA-Z]+[^>]*?>)/g, " =** ");
show(obj.innerHTML)
                    obj.innerHTML = obj.innerHTML.replace(/(<[a-zA-Z]+[^>]*?>)/g, " **= ");
show(obj.innerHTML)
                }
            }

            function tagsAdd() {
                var obj = document.getElementById('content');
                if (obj) {
                    var text = obj.innerHTML;
show(text)
                    for (var i = 0; i < tagsClose.length; i++) {
                        text = text.replace(" =** ", tagsClose[i])
show(text)
                    }

                    for (var i = 0; i < tagsOpen.length; i++) {
                        text = text.replace(" **= ", tagsOpen[i])
show(text)
                    }
show(text)
                    obj.innerHTML = text;
                }
            }
function show(str) {
	document.getElementById('msg').innerHTML+='<xmp'+'>'+str+'</xmp><hr>';
	}

            /*]]>*/
        </script>
        <input type="button" value="Remove Tags" onclick="tagsRemove()" />
        <input type="button" value="Add Tags" onclick="tagsAdd()" />

    </body>
</html>

Open in new window

0
hankknightAuthor Commented:
The biggest problem was that text.replace was used to replace text.  So I used text.split instead.
0
Michel PlungjanIT ExpertCommented:
Great
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
JavaScript

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.