Can you create a JavaScript string without using ' or " quotes?

前端 未结 5 1627
生来不讨喜
生来不讨喜 2020-12-15 12:51

I have a JS file with some XML in it, where the XML is supposed to get converted to a word by the server.

E.g.

var ip = \"

        
相关标签:
5条回答
  • 2020-12-15 13:04

    Using String prototype:

    String(/This contains no quotes/).substring(1).slice(0,-1)
    

    Using String.fromCharCode

    String.fromCharCode(72,69,76,76,79)
    

    Generate Char Codes for this:

    var s = "This contains no quotes";
    var result = [];
    for (i=0; i<s.length; i++)
    {
        result.push(s.charCodeAt(i));
    }
    result
    
    0 讨论(0)
  • 2020-12-15 13:06

    You can't create a string without using a single or double quote, as even calling the String() prototype object directly still requires you to pass it the string.

    Inside XML you would use CDATA, but inside JS you'll have to just escape the '\"strings\"' "\'appropriately\'"

    0 讨论(0)
  • 2020-12-15 13:08

    I was looking for a solution to the same problem. Someone suggested looking at https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/template_strings which proved helpful. After reading about half the article, it stated that you can create strings with the backward tick character. (`)

    Try this :)

    document.getElementById('test').innerHTML = `'|'|'|"|"`
    <div id="test" style="font-size:3em;"></div>

    0 讨论(0)
  • 2020-12-15 13:14

    In JavaScript, you can escape either type of quote with a \.

    For example:

    var str = "This is a string with \"embedded\" quotes.";
    var str2 = 'This is a string with \'embedded\' quotes.';
    

    In particular, your block of JavaScript code should be converted to:

    var ip = "<lang:cond><lang:when test=\"$(VAR{'ip_addr'})\">$(VAR{'ip_addr'})</lang:when></lang:cond>";
    

    In general, I always prefer to escape the quotes instead of having to constantly switch quote types, depending upon what type of quotes may be used within.

    0 讨论(0)
  • 2020-12-15 13:27

    I have had to create strings without quotes for a project as well. We were delivering executable client javascript to the browser for an internal website. The receiving end strips double and single quotes when displayed. One way I have found to get around quotes is by declaring my string as a regular expression.

    var x = String(/This contains no quotes/);
    x = x.substring(1, x.length-1);
    x;
    
    0 讨论(0)
提交回复
热议问题