Nesting quotes in JavaScript/HTML

你说的曾经没有我的故事 提交于 2019-11-26 12:28:13

问题


How do you nest quotes in HTML beyond the second level? As far as I know, there are only 2 types of quotes - single(\') and double(\"). I am aware of escaping using slashes - you have to escape in the code but that escaping won\'t work at the browser level. What is the accepted method to get around something like the following?

<p onclick=\"exampleFunc(\'<div id=\"divId\"></div>\');\">Some Text</p>

That code prints to the browser:

\');\">Some Text


回答1:


You need to use proper escaping/encoding. Either in HTML using character references:

<p onclick="exampleFunc('&lt;div id=&quot;divId&quot;&gt;&lt;/div&gt;');">Some Text</p>

Or in JavaScript using string escape sequences:

<p onclick="exampleFunc('\x3Cdiv\x20id\x3D\x22divId\x22\x3E\x3C/div\x3E');">Some Text</p>



回答2:


Edit: this is not a solution for JavaScript in HTML, but for JavaScript only. My bad...

eval('eval(\"eval(\\\"alert(\\\\\\\"Now I\\\\\\\\\\\\\\\'m confused!\\\\\\\")\\\")\")');

Link. It's "recursive escaping".




回答3:


    const _advanceEscapeCount = (escapeCount, level) => {
      const linearPosition = Math.log(escapeCount + 1) / Math.log(2);
      return Math.pow(2, (linearPosition + level)) - 1;
    };

    const deepNestQuotes = (str, level) => {
      for (let i = str.length - 1; i >=0 ; i--) {

        if (str[i] === '"') {

          const index = i;
          let count = 0;
          while (str[i - 1] === '\\') {
            count++;
            i--;
          }

          const firstPart = str.substr(0,index - count);
          const lastPart = str.substr(index,str.length);

          const escapedCount = _advanceEscapeCount(count, level);
          str = firstPart +  '\\'.repeat(escapedCount) + lastPart;
          //str = firstPart +  escapedCount + lastPart;
        }
      }

      return str;
    };



    deepNestQuotes("1st-level-begin \"2nd-begin   \\\"3rd-begin  \\\\\\\"4th level\\\\\\\"   3rd-end\\\"   2nd-end\" 1st-level-end", 1);

    deepNestQuotes("1st-level-begin \"2nd-begin   \\\"3rd-begin  \\\\\\\"4th level\\\\\\\"   3rd-end\\\"   2nd-end\" 1st-level-end", 2);



回答4:


you need to escape the characters using the \

so your code should look like

<p onclick="exampleFunc('<div id=\"divId\"></div>');">Some Text</p>

Here is some info on Special Characters



来源:https://stackoverflow.com/questions/3039765/nesting-quotes-in-javascript-html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!