mrk m
mrk m

Reputation: 155

Parse HTML string containing script tag and document.write

I have below string. It has nested document.write string statements. I want to add text contents of innermost script to document.

"document.write('<script>document.write(\"<script>document.write(\"Hello World\");<\/script>\");<\/script>')"

How can I parse this string so that Hello World gets added in document. For e.g. html output can be as below.(can be in body or div, anything is ok.)

<body>Hello World</body>

P.S. there can be any number of nested document.write statements. Need to parse this string which can handle n level of nesting.

Upvotes: 0

Views: 1646

Answers (2)

mrk m
mrk m

Reputation: 155

Well I figured it out now.

    var str = "document.write('<script>document.write(\"<script>document.write(\"Hello World\");<\/script>\");<\/script>')";
    var aStr, scriptEle = document.createElement('script');
    aStr = str.replace(/["']/g, '"');
    aStr = aStr.replace(/"<script>document.write/g, "");
    aStr = aStr.replace(/;<\/script\>"/g, "");
    scriptEle.innerHTML = aStr;
    // console.log(aStr);
    document.body.appendChild(scriptEle);

This also handles n level of nesting.

Upvotes: 1

Pramod Solanky
Pramod Solanky

Reputation: 1690

You will basically have to tell the script to execute the script inside the <script> tags. You can achieve this by doing this

var code = "<script>document.write(\"Hello World\");</scr"+"ipt>";
$('body').append($(code)[0]);

Which will happily display hello world in the body tags. You can use this approach to get your script executed by appending it on any tag. Here is the jsfiddle and an SO answer that can give you an idea as to how to be able to execute a js which gets appended dynamically

Hope that helps :)

Upvotes: 0

Related Questions