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

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 = "<lang:cond><lang:when test="$(VAR{'ip_addr'})">$(VAR{'ip_addr'})</lang:when></lang:cond>";

This gets converted to:

var ip = "192.168.0.0";

However, in case the server doesn't work as intended, I don't want there to be a syntax error, and this is VERY important. Currently there would be a syntax error because the language uses both types of quotes. I can't think of a way to get around this, but perhaps there's another way to do quotes in JavaScript? Or to create a string?

For example, in Python I'd use triple quotes:

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

Anyone have a bright idea?

Answers:

Answer

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;
Answer

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
Answer

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.

Answer

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>

Answer

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\'"

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.