-1

It's hard to describe this question in the title, as an example will make sense of what I'm trying to do.

I have a JS object that I want to add to:

jsTestObj = [ ]

On each call to strings of data, I want to add a key and a value pair:

var pushTestObj = { };
pushTestObj["myKey"] = "MyName";
pushTestObj["myValue"] = "I call myself "Joe""; // these strings may have apostrophes, quotes, or even comments that are legit
jsTestObj.push(pushTestObj);

I need to retain all quotes or parenthesis in these fields (and comments, which are also possible and match JS comments). In a sense, I am looking for a possible function (method) that simply wraps the string like:

pushTestObj["myValue"] = wrapStringMethodToRetainCharacters(I call myself "Joe");

Where JS will know it's a string in the value "myValue" and retain the quotes, apostrophes and comments, while still storing it in a string.

Escape Characters

This will work for quotes and apostrophes; what about comments. For example:

var pushTestObj = { };
    pushTestObj["myKey"] = "MyName";
    pushTestObj["myValue"] = "/* He's "different" */ Sometimes David; // these strings may have apostrophes, quotes, or even comments that are legit
    jsTestObj.push(pushTestObj);
WhyAShortage
  • 121
  • 1
  • 2
  • 9
  • `pushTestObj["myValue"] = "I call myself "Joe"";` That's a syntax error, not more, not less - you have to escape the `"`. – baao Feb 23 '17 at 14:35
  • 1
    Possible duplicate of [Escaping Strings in JavaScript](http://stackoverflow.com/questions/770523/escaping-strings-in-javascript) – Mistalis Feb 23 '17 at 14:36
  • @Mistalis it is a duplicate, the problem is OP didn't even know that he/she is looking for `escape characters`... – Megajin Feb 23 '17 at 14:40

2 Answers2

1

If you want to retain special characters just escape them with a \.

Here is an example:

pushTestObj['myValue'] = 'I call myself \"Joe\"';

Special characters always need to be escaped. Escaped characters will be put into a string as they are.

Just a side note your code as it is shouldn't be able to be run without a syntax error.

Megajin
  • 2,648
  • 2
  • 25
  • 44
1

It seems you are looking for escaping:

pushTestObj["myValue"] = "I call myself \"Joe\""; // these strings may have apostrophes or single quotes that are legit

pushTestObj["myValue"] = "/* He's \"different\" */ Sometimes David"; // these strings may have apostrophes, quotes, or even comments that are legit

A string can contain apostrophes or single quotes, no problem there. However you cannot type them in a string literal without escaping.

Comments have no special meaning inside a string.

It really helps if you get an texteditor with syntax highlighting, as it will quickly show you where a string starts and ends.