Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Script tag in JavaScript string [duplicate]

Tags:

javascript

I am encountering an issue where having a ending script tag inside a quoted string in JavaScript, and it is killing the script. I assume this is not expected behaviour. An example of this can be seen here: http://jsbin.com/oqepe/edit

My test case browser for the interested: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.4) Gecko/20091028 Ubuntu/9.10 (karmic) Firefox/3.5.4.

like image 560
re5et Avatar asked Nov 02 '09 06:11

re5et


People also ask

How do you duplicate a string in JavaScript?

repeat() is an inbuilt function in JavaScript which is used to build a new string containing a specified number of copies of the string on which this function has been called. Syntax: string. repeat(count);

Can you multiply a string in JavaScript?

There are three ways you can multiply the string above: Using the String. repeat() method. Using a for loop.

How does repeat work in JavaScript?

JavaScript String repeat()The repeat() method returns a string with a number of copies of a string. The repeat() method returns a new string. The repeat() method does not change the original string.


1 Answers

What happens?

The browser HTML parser will see the </script> within the string and it will interpret it as the end of the script element.

Look at the syntax coloring of this example:

<script> var test = 'foo... </script> bar.....'; </script> 

Note that the word bar is being treated as text content outside of the script element...

A commonly used technique is to use the concatenation operator:

var test = '...... </scr'+'ipt>......'; 
like image 77
Christian C. Salvadó Avatar answered Sep 19 '22 09:09

Christian C. Salvadó