I'm working on a project where we use both asp and Javascript to create the front end of it. We have a table where users input strings that can have both single and double quotes at times. My code handles only one of the quotes at a time. How do I make my code handle both of it at the same time?
<td <%=cl%> style="width:<%=colwid(c)-4%>;text-align:<%=align(c)%>;" **origvalue="<%=cell%>"**><%=cell%></td>
original value holds the string.
In order to have a string contain the same type of quotes you used to delimit the string, you have to escape the quote characters. In other words, you have to put a \ character before the quote character you want to use in your string.
For example:
console.log('\'Hello world!\''); // prints 'Hello world!'
console.log("\"Hello world!\""); // prints "Hello world!"
console.log(`\`Hello world!\``); // prints `Hello world!`
You only need to escape the quote characters which match the string's delimiters, but you can escape any of the quote characters in any type of JS string.
Related
Using a regular expression, I can't find a solution to wrap each field from a csv text into double quotes.
The issue is that there could be already double-quoted fields.
Example:
Country;Product Family;Product SKU;Commercial Status
Germany;Aprobil;"Apro&'bil_1_5 mL";Actively Marketed
Should be
"Country";"Product Family";"Product SKU";"Commercial Status"
"Germany";"Aprobil";"Apro&'bil_1_5 mL";"Actively Marketed"
Basically, I have a problem to get two logical part in a regular expression...
Thanks in advance!
You will need to to do 2 replacements, I think, first regex looks like this:
/([\w ]+[^;\n]*|\"[^\"]*\")/g
The regex will either match:
Any Word character or Space, 1 or more times, followed by any char not being semi colon ';' or newline, any number of times.
A double quote followed by any characters not being double quote, any number of times, ending with a double quote.
You then replace the matches with: \"\1\".
Fianally you replace 2 double quotes with a single one.
In JavaScript this is:
var test = 'Country;Product Family;Product SKU;Commercial Status\n'
+ 'Germany;Aprobil;"Apro&'bil_1_5 mL";Actively Marketed\n';
var regex = /([\w ]+[^;\n]*|\"[^\"]*\")/g;
test = test.replace(regex, '\"\1\"'); // wrap in double quotes
test = test.replace(/\"\"/g, '\"'); // replace 2 quotes with one
Now you should have what you want.
I'm trying to find strings enclosed in single quotes with this regex : /'+(.*?)'+,?/g
The problem is that single quotes are allowed inside the string as long as they are escaped with a second quote: 'it''s, you''ve, I''m... and so on, ends with one more single quote '''.
My regex breaks if there are any amount of single quotes inside and ends up skipping quotes in the beginning and end of the match if there are any.
It seems to work perfectly as long as nobody adds any quotes inside the string. But this is not how the real world works unfortunately.
How can I make my regex include the quotes in the match?
try this regex:
'(?:''|[^'])*'
explanation: single quote followd by (two quotes OR a non quote char) repeated as necessary, followed by a closing single quote.
https://regex101.com/r/R4sd47/1
I was converting normal string in to latex format.So i was created the latex code match and replace the \ single slash into \\ double slash.why the i need it Refer this link.I tried Below code :
function test(){
var tex="$$\left[ x=\left({{11}\over{2}}+{{\sqrt{3271}}\over{2\,3^{{{3}\over{2} $$";
var tex_form = tex.replace("/[\\\/\\\\\.\\\\]/g", "\\");
document.getElementById('demo').innerHTML=tex_form;//nothing get
}
test();
<p id="demo"></p>
Not getting any output data.But the match in this link
i wish to need replace the \ into \\
There are these issues:
The string literal has no backslashes;
The regular expression is not a regular expression;
The class in the intended regular expression cannot match sequences, only single characters;
The replacement would not add backslashes, only replace with them.
Here you find the details on each point:
1. How to Encode Backslashes in String Literals
Your tex variable has no backslashes. This is because a backslash in a string literal is not taken as a literal backslash, but as an escape for interpreting the character that follows it.
When you have "$$\left...", then the \l means "literal l", and so the content of your variable will be:
$$left...
As an l does not need to be escaped, the backslash is completely unnecessary, and these two assignments result in the same string value:
var tex="$$\left[ x=\left({{11}\over{2}}+{{\sqrt{3271}}\over{2\,3^{{{3}\over{2} $$";
var tex="$$left[ x=left({{11}over{2}}+{{sqrt{3271}}over{2,3^{{{3}over{2} $$";
To bring the point home, this will also represent the same value:
var tex="\$\$\l\e\f\t\[\ \x\=\l\e\f\t\(\{\{\1\1\}\o\v\e\r\{\2\}\}\+\{\{\s\q\r\t\{\3\2\7\1\}\}\o\v\e\r\{\2\,\3\^\{\{\{\3\}\o\v\e\r\{\2\}\ \$\$";
If you really want to have literal backslashes in your content (which I understand you do, as this is about LaTeX), then you need to escape each of those backslashes... with a backslash:
var tex="$$\\left[ x=\\left({{11}\\over{2}}+{{\\sqrt{3271}}\\over{2\\,3^{{{3}\\over{2} $$";
Now the content of your tex variable will be this string:
$$\left[ x=\left({{11}\over{2}}+{{\sqrt{3271}}\over{2\,3^{{{3}\over{2} $$
2. How to Code Regular Expression Literals
You are passing a string literal to the first argument of replace, while you really intend to pass a regular expression literal. You should leave out the quotes for that to happen. The / are the delimiters of a regular expression literal, not quotes:
/[\\\/\\\\\.\\\\]/g
This should not be wrapped in quotes. JavaScript understands the / delimiters as denoting a regular expression literal, including the optional modifiers at the end (like g here).
3. Classes are sets of single characters
This regular expression has unnecessary characters. The class [...] should list all individual characters you want to match. Currently you have these characters (after resolving the escapes):
\
/
\
\
.
\
\
It is overkill to have the backslash represented 5 times. Also, in JavaScript the forward slash and dot do not need to be escaped when occurring in a class. So the above regular expression is equivalent to this one:
/[\\/.]/g
Maybe this is, or is not, what you intended to match. To match several sequences of characters, you could use the | operator. This is just an example:
/\\\\|\\\/|\\\./g
... but I don't think you need this.
4. How to actually prefix with backslashes
It seems strange to me that you would want to replace a point or forward slash with a backslash. Probably you want to prefix those with a backslash. In that case make a capture group (with parentheses) and refer to it with $1 in this replace:
tex.replace(/([\\/.])/g, "\\$1");
Note again, that in the replacement string there is only one literal backslash, as the first one is an escape (see point 1 above).
why the i need it
As the question you link to says, the \ character has special meaning inside a JavaScript string literal. It represents an escape sequence.
Not getting any output data.But the match in this link
The escape sequence is processed when the string literal is parsed by the JavaScript compiler.
By the time you apply your regular expression to them, they have been consumed. The slash characters only exist in your source code, not in your data.
If you want to put a slash character in your string, then you need to write the escape sequence for it (the \\) in the source code. You can't add them back in with JavaScript afterwards.
Not sure if I understood the problem, but try this code:
var tex_form = tex.replace("/(\\)/g","\\\\");.
You need to use '(' ')' instead of '['']' to get a match for output.
I want to generate the string "\" in Javascript but couldn't seem to do it. If I only write "\", I would get compile time error because " itself is escaped. But if I do "\\", I would get two slashes as the output. So how do I generate a string with a single forward slash?
The character / is a slash. The character \ is a backslash.
Backslash \ is used as an escape character for strings in JavaScript, and in JSON. It is required for some characters to remove ambiguity from string literals. This string is ambiguous:
'He's going to the park'
There are three single quote ' marks, and the parser doesn't know what is part of the string and what isn't. We can use a backslash to escape the one that we want to represent the character ' instead of the close of the string literal (also ').
'He\'s going to the park'
Now, if the backslash has special meaning, how do we represent a literal backslash \ character in the string? By simply escaping the backslash \ with a backslash \.
'C:\\DOS\\command.com' // In memory this is: C:\DOS\command.com
Remember that this escaping is only for the text representation of strings in code or JSON. The code is parsed and the strings in memory are what we would expect, with all escaping resolved to the proper characters.
Now your question asks about JSON and makes the assumption that this is incorrect:
I am writing '\' as the key to a JSON package. The result is something like "READY_TO_PRINT_DATE":"/\\Date(1403911292:981000+420)\\/".
JSON requires the same escaping as you find in JavaScript, and for the same reason... to remove ambiguity from strings. The JSON-version of the string /\\Date(1403911292:981000+420)\\/ is how you would properly represent the actual string /\Date(1403911292:981000+420)\/.
I hope this helps clears up some of your confusion.
you can escape the slash:
myvar = "\\";
I am of the understanding that if I am trying to stringify quotes (' and "), i need to escape them but I can't explain the following results when I tried the same out in firebug:
1. >> JSON.stringify({foo: "a"a'a"});
SyntaxError: missing } after property list
Inference: This is expected since I didn't escape " and '
2 >>> JSON.stringify({foo: "a\"a'a"});
"{"foo":"a\"a'a"}"
Inference/Question: Will the JSON string also show the escape character before " and why it works without escaping the single quote
Also JSON throws an error when I try to parse the output string generated above back to JS object ?
>>> JSON.parse("{"foo":"a\"a'a"}")
SyntaxError: missing ) after argument list
Finally Explain results below: Basically if I escape the single quote once, it doesn't show up in the output string but if I escape twice, it does
>>> JSON.stringify({foo: "a\"a\'a"});
"{"foo":"a\"a'a"}"
>>> JSON.stringify({foo: "a\"a\\'a"});
"{"foo":"a\"a\\'a"}"
Basically I am trying to understand when and how I need to escape single and double quotes when converting to and from JSON.
Thanks for your help
EDIT:
Thanks for the replies .
The first 2 queries are clear. So I only need to escape the quotes I am using to enclose the string ( in my case ") and escape any escape characters itself in the string. Other than these 2, I don't need to escape any other chars?
I am not clear on the last query. If I just increase the escape characters before ', why does it shows even number of escape chars in the output . For eg
>>> JSON.stringify({foo: "a\"a\'a"});
"{"foo":"a\"a'a"}"
>>> JSON.stringify({foo: "a\"a\\'a"});
"{"foo":"a\"a\\'a"}"
>>> JSON.stringify({foo: "a\"a\\\'a"});
"{"foo":"a\"a\\'a"}"
The format given by your JavaScript interpreter here is a little misleading when it outputs the following:
2 >>> JSON.stringify({foo: "a\"a'a"});
"{"foo":"a\"a'a"}"
The interpreter is adding the double quotes on the outside without doing any of the necessary escaping to make the result a valid string literal, so what this is actually trying to say is that the result of the expression is a string that contains {"foo":"a\"a'a"} (where every character there is literal, including the backslash). If you were going to write this as a JavaScript string literal it would be one of the following:
With double quotes: "{\"foo\":\"a\\\"a'a\"}"
With single quotes: '{"foo":"a\\"a\'a"}'
The above strings are exactly identical, they are just represented differently based on which external quote is used. You should be able to pass either of those strings to JSON.parse and get an object equivalent to what you started with.
Hopefully this will also help to clarify as to why the single quote isn't escaped, as shown above you only need to escape the type of quote that is used for the string literal (so escape internal double quotes if double quotes surround the string, and escape internal single quotes when single quotes are around the string).
So the errors being thrown is because the string is being ended. So any other characters that follow are attempted to be parsed but aren't able to be. Hence the errors.
So because you start with a quotation mark ("), using an apostrophe (') isn't ending the string. It's within the string, because your string is expected to end with another quotation mark.
If you want to include the same character that the string is defined within, it will need to be escaped. E.g. " and he said \"what a great day!\" to the other boy"
No need to escape single quotes inside of double quotes, or double quotes inside of single quotes.
You do need to escape like quotes within like quotes -- these are all valid syntax:
var a = "Testing '1234'";
var b = 'Testing "1234"';
var c = "Testing \"1234\"";
var d = 'Testing \'1234\'';
Second piece, on JSON stringification, the double quotes you see output here:
JSON.stringify({foo: "a\"a'a"});
"{"foo":"a\"a'a"}"
are just an output within whatever console or repl you are using. Technically those should be output as single quotes.
At any rate...
var s = JSON.stringify({foo: "a\"a'a"});
JSON.parse(s);
...will most definitely output a valid object.
Your first inference is correct; you need to escape any special characters (Quotation marks, in this case) that you want to appear in your final string. If you don't, then the browser will try to parse the string as-is, and will fail miserably because of mismatched quotes.
This is the same reason you get an error when you're parsing the string; the parser can't account for the mismatched quotes.
For the last behaviour you were having trouble with, you're not really escaping the quote twice; you're escaping the escape character.