Single quotes not being replaced in javascript? - javascript

I'm trying to sanitize quotes from a text input. Right now my code is:
string = string.replace(/'/g, '\'');
string = string.replace(/"/g, '\"');
My out put has all double quotes replaced, but the single quotes remain. I am fairly confident in my regex, and haven't had a problem with the replace function before. Is there a chance that mySQLdb is messing this up? I am posting it and then getting almost immediately after. This seems like such a simple issue but it really has me stumped

Your replacements are null operations since the backslash is consumed by the string literal itself and is not present in the actual string value.
Instead escape the backslash to really get one in your string:
string = string.replace(/'/g, "\\'");
string = string.replace(/"/g, '\\"');
You can of course do this in one operation:
string = string.replace(/(['"])/g, "\\$1");

Related

Javascript .replace() of the character " with the characters \"

I am trying to pass a JSON string to a C# .exe as a command line argument, from Javascript as a node.js child-process. For the sake of argument my JSON looks something like this:
string jsonString = '{"name":"Tim"}'
The issue with passing this as a C# arg is that the double quotation marks must be retained if I hope to parse it in the C# code. As such, what I need to pass into the C# command line needs to look something like this, where I escape the double quotation mark:
string jsonStringEscaped = '{\"name\":\"Tim\"}'
The motivation for doing this is that it allows me to maintain a consistent object structure across the two languages, which is obviously highly desirable for me.
In order to achieve this, I am attempting to use the Javascript .replace() method prior to sending the argument to the C#, and to do this I use a simple RegEx:
string jsonStringEscaped = jsonString.replace(/\"/g,"\\\"")
Unfortunately, this returns something of the form '{\\"name\\":\\"Tim\\"}' which is useless to me.
I have tried variations on this:
string jsonStringEscaped = jsonString.replace(/\"/g,"\\ \"")
\\ returns '{\\ "name\\ ":\\ "Tim\\ "}'
string jsonStringEscaped = jsonString.replace(/\"/g,"\\\\")
\\ returns '{\\\\name\\\\:\\\\Tim\\\\}'
string jsonStringEscaped = jsonString.replace(/\"/g,"\\\")
\\ is invalid
string jsonStringEscaped = jsonString.replace(/\"/g,"\\\ ")
\\ returns '{\\ name\\ :\\ Tim\\ }'
I have tried variations where the second .replace() argument is contained within single quotation marks '' rather than double quotation marks "" with no success.
Can anyone tell me what I am doing wrong? Better yet, can anyone suggest a more efficient method for doing what I am trying to achieve?
Unless I'm misreading you, I think you're just trying to escape a character that doesn't need to be escaped in your regex (").
var jsonString = '{"name":"Tim"}'
var escaped = jsonString.replace(/"/g, '\\"');
// escaped == "{\"name\":\"Tim\"}"

How to find out if a given string is HTML Escaped or not?

Is there any method to find out if the given string is HTML Escaped or not?
Consider the following javascript code:
<script>
var str="hello";
var str_esc=escape(str);
document.write(isHTMLEscaped(str)) // *Should print False*
document.write(isHTMLEscaped(str_esc)); // *Should print True*
</script>
Is there any method equivalent to isHTMLEscaped in the above case?
I found that using
escape(unescape(str))
will always provide an escaped string. And the unescape string will do nothing unless the string itself contains escaped expressions.
Note: should have used encodeURI(decodeURI(str)) instead as escape is now depreciated.
As "hello"==escape("hello"), no, you can't at all guess if escaping was applied.
If you want to know if it's probable that the string has been escaped, then you might test
var wasProbablyEscaped = /%\d\d/.test(str);
var wasProbablyNotEscaped = !wasProbablyEscaped && /%\d\d/.test(escape(str));
as escaping adds % followed by two digits when something has to be escaped. But you can't be totally sure as some strings don't change when you escape them.
In your case, I'd probably advise you not to escape if wasProbablyEscaped is true.

carriage return encoding

through queries to a Database I am retrieving such data that I previously inserted through HTML textarea or input. When I get the response from my DB , in a JSON object the text field looks like this :
obj : {
text : [some_text] ↵ [some_text]
}
I tried to replace with this function :
string_convert = function(string){
return string.replace("&#8629",'<br>')
.replace('&crarr','<br>')
.replace('/[\n\r]/g','<br>');
}
I have to show this string in HTML ,but it does not seems to work. I'm using UTF-8
Any advice?
The problem you have is that you have enclosed your regex in quotes. This is incorrect.
.replace('/[\n\r]/g','<br>');
^ ^
remove these two quotes
The quotes are unnecessary because the regex is already delimited by the slashes.
By putting quotes in there, you've actually told it that you want to replace a fixed string rather than a regular expression. The fixed string may look like an expression, but with the quotes, it will just be seen as a plain string.
Remove the quotes and it will be seen as an expression, and it will work just fine.
One other thing, though -- in order to make your regex work perfectly, I'd also suggest modifying it slightly. As it stands, it will just replace all the \n and \r characters with <br>. But in some cases, they may come together as a \r\n pair. This should be a single line break, but your expression will replace it with two <br>s.
You could use an expression like this instead:
/\r\n|\n|\r/g
Hope that helps.
you are missing the ending semicolons ; in your code:
string_convert = function(aString){
return aString.replace("↵",'<br>').replace('↵','<br>');
}
this does not necessary solve your problem, but it could likely.
From: Trying to translate a carriage return into a html tag in Javascript?
text = text.replace(/(\r\n|\n|\r)/g,"<br />");

Json String with comment out quotes in variable

I have a JSON string hardcoded in my Javascript.
valiJsonString = '{"ssss","ddddddddd\"ddd"}';
The DOM says -> {"ssss","ddddddddd"ddd"}
Can someone tell me why javascript replace my \" into " ?
// try to parse
valiJsonString secureEvalJSON (valiJsonString) //<-- error: jsonString is not valid
working example
"The DOM says" doesn't make much sense, as the DOM doesn't say anything. Do you mean the object browser in Firebug (or some other development console)?
Now, inside a string, \" is the quote character. You have to compensate for this escaping since you do not want it, but instead a verbatim slash.
So perhaps you want \\ followed by ", which is the slashed character followed by the quote character.
In addition, the given JSON looks like it ought to represent an array not an object, since you have no keys:
var str = '["ssss","ddddddddd\\"ddd"]';
The actual value of this JSON-format string inside your browser is now:
["ssss","ddddddddd\"ddd"]
\ is an escape character. try \\
If you want your string to come through escaped, then you need to escape your escape character:
valiJsonString = '{"ssss","ddddddddd\\"ddd"}';
I've added second \ (\ is escape char) and fixed lack of = and type of table {} vs []
http://jsfiddle.net/4wVaR/9/

JQuery escape apostrophes and double apostrophes?

I want to use JQ to print to a div on my page. The string I want to print with contains HTML including apostrophes and double apostrophes.
Is there a plugin or function to escape this so that the string doesnt break the js variable? There may be the case that I can't escape all of the apostrophes and double apostrophes in the incoming data using a backslash, so I'm looking for a function that can do it.
EG;
var replacement = 'This content has an apostrophe ' and a double apostrophe "';
$("#overwrite").text(replacement);
TIA
If you wanted to type out a string that is assigned to a variable like in your example above, then just escape it yourself.
For example, if I know my data will have apostrophes, then I wrap it in quotes (what you are calling double apostrophes) and use the HTML shortcut for quotes " or you can use a backslash to escape the quote \". Either way works. So your example above would become:
var replacement = "This content has an apostrophe ' and a double apostrophe "";
If the user is typing in the string or you are getting data from a feed, then it would be best to use the javascript replace function to make sure the quotes are escaped, like this:
var text = $("input").val().replace(/\"/g,""");
There is no need to escape incoming data, as it is already a string.
The only reason you need to escape apostrophes and double apostrophes in JavaScript source is due to the fact the JavaScript engine has to determine where the string starts and ends.
For instance, assuming you have a div#source containing the text "Hi there, what's up!", it is perfectly safe to do $("#overwrite").text($("#source").text()).

Categories