0

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.

2
  • 1
    And the question is? Commented Nov 27, 2014 at 13:09
  • could you please give with an example where you want to add. if you create example it will be easily understandable take two string in which show actual string and in other string show where you want to insert Commented Nov 27, 2014 at 13:47

2 Answers 2

1

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.

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

Comments

0

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 :)

2 Comments

Thanks for your help. But I can't split string as this string comes from server and it can have multiple </script> tags. Also there can be any number of document.write statements. I figured out answer with pure js.
Some compilers like Babel are smart and then concat the string in a single string. At runtime it breaks the JS execution

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.