var test = [
'Mercu"ry', 'Mercu,ry', 'Mer"cu,ry', 'Mercury'
];
for (x in test) {
var s = test[x];
if (s.indexOf('"') != -1) {
s = s.replace(/"/g, '""');
}
if (s.match(/"|,/)) {
s = '"' + s + '"';
}
alert(s);
}
Test: http://jsfiddle.net/ZGFV5/
Try to run the code with Mer""cury :)
var test = [
'Mercu"ry', 'Mercu,ry', 'Mer"cu,ry', 'Mercury'
];
for (x in test) {
var s = test[x];
if (s.indexOf('"') != -1) {
s = s.replace(/"/g, '""');
}
if (s.match(/"|,/)) {
s = '"' + s + '"';
}
alert(s);
}
Test: http://jsfiddle.net/ZGFV5/
Try to run the code with Mer""cury :)
Just always wrap the word in double quotes, and replace all double quotes with two:
function escapeWord(word) {
return '"' + word.replace(/"/g, '""') + '"';
}
javascript - Regular expression to escape double quotes within double quotes - Stack Overflow
How do I replace a double-quote with an escape-char double-quote in a string using JavaScript? - Stack Overflow
Escaping Single and Double Quotes in a generated String - JavaScript - SitePoint Forums | Web Development & Design Community
javascript - Escape double quotes within double quotes with Regex[JS] - Stack Overflow
I tried it just for fun, even though it is certainly better to fix the generator. This might work in your case, or at least inspire you:
You can try it here
$( function()
{
var myString = "{ \"na\"\"me\": \"va\"lue\", \"tes\"\"t\":\"ok\" }";
var myRegexp = /\s*\"([\w\"]+)\"\s*[,}:]/g;
var match;
var matches = [];
// Save all the matches
while((match = myRegexp.exec(myString)) !== null)
{
matches.push(match[1]);
console.log(match[1]);
}
// Process them
var newString = myString;
for (var i=0; i<matches.length; i++)
{
var newVal = matches[i].replace(/\"/g, '\\\"');
newString = newString.replace(matches[i], newVal);
}
alert(myString + "\n" + newString);
}
);
You can try, although this will work only for the opening tags :
.replace(/\"\"/g, '\\""');
You need to use a global regular expression for this. Try it this way:
str.replace(/"/g, '\\"');
Check out regex syntax and options for the replace function in Using Regular Expressions with JavaScript.
Try this:
str.replace("\"", "\\\""); // (Escape backslashes and embedded double-quotes)
Or, use single-quotes to quote your search and replace strings:
str.replace('"', '\\"'); // (Still need to escape the backslash)
As pointed out by helmus, if the first parameter passed to .replace() is a string it will only replace the first occurrence. To replace globally, you have to pass a regex with the g (global) flag:
str.replace(/"/g, "\\\"");
// or
str.replace(/"/g, '\\"');
But why are you even doing this in JavaScript? It's OK to use these escape characters if you have a string literal like:
var str = "Dude, he totally said that \"You Rock!\"";
But this is necessary only in a string literal. That is, if your JavaScript variable is set to a value that a user typed in a form field you don't need to this escaping.
Regarding your question about storing such a string in an SQL database, again you only need to escape the characters if you're embedding a string literal in your SQL statement - and remember that the escape characters that apply in SQL aren't (usually) the same as for JavaScript. You'd do any SQL-related escaping server-side.
Just a small question about quotation marks in regular expression patterns since it's causing me a little bit of confusion. Why are those two different:
(.pattern #"\"") ;=> "\\\"" (.pattern (re-pattern "\"")) ;=> "\""
when evaluation of
(re-pattern "\"")
yields
#"\""
?
(Or the other way round: why is (re-pattern "\"") the same as (re-pattern "\\\"") ?)
Do quotation marks really have to be escaped? If so, what exactly is their special meaning?
They do match the same strings, I just happen to need the pattern string for processing and now I can't be sure when to remove a backslash before a quotation mark...
The thing is that .replace() does not modify the string itself, so you should write something like:
strInputString = strInputString.replace(...
It also seems like you're not doing character escaping correctly. The following worked for me:
strInputString = strInputString.replace(/'/g, "\\'");
Best to use JSON.stringify() to cover all your bases, like backslashes and other special characters. Here's your original function with that in place instead of modifying strInputString:
function testEscape() {
var strResult = "";
var strInputString = "fsdsd'4565sd";
var strTest = "strResult = " + JSON.stringify(strInputString) + ";";
eval(strTest);
alert(strResult);
}
(This way your strInputString could be something like \\\'\"'"''\\abc'\ and it will still work fine.)
Note that it adds its own surrounding double-quotes, so you don't need to include single quotes anymore.
Hey,
I'm creating an object which contains user-typed content and the very same object will be printed / embeded somewhere else after. The tricky thing is :
- The object uses "xxx" for strings
- The place where it will be embeded as a text uses '{"mykey" : "myobject"}'
The object's creation is done using js ; the embed is in a bash environment. These are two separate scripts. So, basically, I want to escape all quotes and single quotes but also avoid escaping a user-typed quote like in this case \', which would output \\' and unescape the quote by escaping the escape itself. When I build my string, it seems that the quotes are successfully replaced with escaped ones. But then when I return the string, is seems that the escape is taken in account so the escapes disappears. What I'm trying to explain is that apparently when I return the escaped string, JS uses it to return the unescaped version.
How can I escape quotes and keep the string escaped for later use ? thanks
It should be:
var str='[{"Company": "XYZ","Description": "\\"TEST\\""}]';
First, I changed the outer quotes to single quotes, so they won't conflict with the inner quotes. Then I put backslash before the innermost quotes around TEST, to escape them. And I escaped the backslash so that it will be treated literally.
You can get the same result with use of a JSON function:
var str=JSON.stringify({Company: "XYZ", Description: '"TEST"'});
Here the inner quote is escaped and the entire string is taken in single quote.
var str = '[{ "Company": "XYZ", "Description": "\\"TEST\\""}]';