简体   繁体   中英

JavaScript adding quotes to output

Here my code:

<!DOCTYPE html> 
  <html> 
    <body>     
      <h2>JavaScript Operators</h2>

      <p>The + operator concatenates (adds) strings.</p>

      <p id="demo"></p>
    </body> 

    <script> 
      var txt1 = '"Jhon"'; 
      var txt2 = "Doe";
      document.getElementById("demo").innerHTML = txt1 + " " + txt2;
    </script>
  </html>

The output would be like Jhon Doe but I want to add quote to the output like "Jhon" "Doe". I know I can do this by adding escape to variable like "Jhon"' or "\\"Jhon\\"" but my variable isn't string in my actual code, this is just an example.

Just trying to make it clear again, I cannot edit string variable value I want to edit the output somewhere here to add the quotes

document.getElementById("demo").innerHTML = txt1 + " " + txt2;

You can double-stringify string variable with JSON.stringify, if I understood you correctly:

 var txt1 = "Jhon"; var txt2 = "Doe"; document.getElementById("demo").innerHTML = JSON.stringify(txt1) + " " + JSON.stringify(txt2); 
 <p id="demo"></p> 

Since the accepted answer uses JSON.stringify() in an inefficient and unintended way, that has worse browser support, not to mention it is unintuitive and odd, I thought I would do it the normal and theoretically faster way.

KEEP IN MIND, the accepted answer is fine for the listed purposes, I simply think it better to do things the intuitive way, you want to add quotes, this is how you add quotes. JSON.stringify() is for creating a JSON string of a variable or object, which happens to add quotes.

Change your text output to look like this:

document.getElementById("demo").innerHTML = '"'+txt1+'"' + " " + '"'+txt2+'"';

You can also use the \\" escape sequence if you so desire.

This is more versatile in quite a few ways, as you can now do things like this:

var quote="\"";
var names=[
    ["John", "Doe"],
    ["Jane", "Doe"],
    ["Jennifer", "Dawn"]
];
names.forEach(function(item,key){
    var txt1=item[0];
    var txt2=item[1];
    document.getElementById("demo").innerHTML += quote+txt1+quote + " " + quote+txt2+quote+"<br/>";
});

Where quote="\\""

Expected output

"John" "Doe"
"Jane" "Doe"
"Jennifer" "Dawn"

Where quote="'"

Expected output

'John' 'Doe'
'Jane' 'Doe'
'Jennifer' 'Dawn'

Etc etc. This makes complex string manipulation much easier, especially when it comes to prices and putting the correct currency symbol.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM