Here is a section of code used by CKEditor on my website:
CKEDITOR.config.IPS_BBCODE = {"acronym":{"id":"8","title":"Acronym","desc":"Allows you to make an acronym that will display a description when moused over","tag":"acronym","useoption":"1","example":"[acronym='Laugh Out Loud']lol[/acronym]", ...
If you scroll to the right just a little, you will see this:
"[acronym='Laugh Out Loud']lol[/acronym]"
I need to store all of the CKEditor code inside a javascript string, but I can't figure out how to do it because the string has both " and ' in it. See the problem? Furthermore, I don't think I can just escape the quotes because I tried doing that and the editor didn't work.
Any idea what I can do?
You might try taking the string and injecting JavaScript escape codes into it. JavaScript can essentially use any unicode value when using the format: \u#### - so, for a ' character, the code is \u0039, and for the " character, the code is \u0034.
So - you could encode your example portion of the string as:
\u0034[acronym=\u0039Laugh Out Loud\u0039]lol[/acronym]\u0034
Alternatively, you could attempt to simply escape the quotes as in:
\"[acronym=\'Laugh Out Loud\']lol[/acronym]\"
The problem here occurs when you wind up with this kind of situation:
"data:{'prop1':'back\\slash'}"
Which, when escaped in this manner, becomes:
"data:{\'prop\':\'back\\\\slash\'}\"
While this is somewhat more readable than the first version - de-serializing it can be a little tricky when going across object-spaces, such as a javascript object being passed to a C# parser which needs to deserialize into objects, then re-serialize and come back down. Both languages use \ as their escape character, and it is possible to get funky scenarios which are brain-teasers to solve.
The advantage of the \u#### method is that only JavaScript generally uses it in a typical stack - so it is pretty easy to understand what part should be unescaped by what application piece.
hmm.. you said you already tried to escape the quotes and it gave problems.
This shouldn't give problems at all, so try this:
$newstring = addslashes($oldstring);
There's no need to use Unicode escape sequences. Just surround your string with double quotes, and put a backslash before any double quotes within the string.
var x = "\"[acronym='Laugh Out Loud']lol[/acronym]\"";
Related
I have an application which uses a Javascript-based rules engine. I need a way to convert regular straight quotes into curly (or smart) quotes. It’d be easy to just do a string.replace for ["], only this will only insert one case of the curly quote.
The best way I could think of was to replace the first occurrence of a quote with a left curly quote and every other one following with a left, and the rest right curly.
Is there a way to accomplish this using Javascript?
You could replace all that preceed a word character with the left quote, and all that follow a word character with a right quote.
str = str.replace(/"(?=\w|$)/g, "“");
str = str.replace(/(?<=\w|^)"/g, "”"); // IF the language supports look-
// behind. Otherwise, see below.
As pointed out in the comments below, this doesn't take punctuation into account, but easily can:
/(?<=[\w,.?!\)]|^)"/g
[Edit:] For languages that don't support look-behind, like Javascript, as long as you replace all the front-facing ones first, you have two options:
str = str.replace(/"/g, "”"); // Replace the rest with right curly quotes
// or...
str = str.replace(/\b"/g, "”"); // Replace any quotes after a word
// boundary with right curly quotes
(I've left the original solution above in case this is helpful to someone using a language that does support look-behind)
You might want to look at what Pandoc does—apparently with the --smart option, it handles quotes properly in all cases (including e.g. ’tis and ’twere).
I recently wrote a Javascript typography prettification engine that does, among other things, quote replacement; I wound up using basically the algorithm suggested by Renesis, but there’s currently a failing test up waiting for a smarter solution.
If you’re interested in cribbing my code (and/or submitting a patch based on work you’ve done), check it out: jsPrettify. jsprettify.prettifyStr does what you’re looking for. If you don’t want to deal with the Closure dependency, there’s an older version that runs on its own—it even works in Rhino.
'foo "foo bar" "bar"'.replace(/"([-a-zA-Z0-9 ]+)"/g, function(wholeMatch, m1){
return "“" + m1 + "”";
});
The following just changes every quote by alternating (this specific example however would leave out the orphaned quotes).
str.replace(/\"([^\"]*)\"/gi,"“$1”");
Works perfectly, as long as the text you're texturizing isn't already screwed up with improper use of the double quote. In English, quotes are never nested.
I don't think something like that in general is easy at all, because you'd have to interpret exactly what each double-quote character in your content means. That said, what I'd do is collect all the text nodes I was interested in, and then go through and keep track of the "on/off" (or "odd/even"; whatever) nature of each double quote instance. Then you can know which replacement entity to use.
I didn't find the logic I wanted here, so here's what I ended up going with.
value = value.replace(/(^|\s)(")/g, "$1“"); // replace quotes that start a line or follow spaces
value = value.replace(/"/g, "”"); // replace rest of quotes with the back smart quote
I have a small textarea that I need to replace straight quotes with curly (smart) quotes. I'm just executing this logic on keyup. I tried to make it behave like Microsoft Word.
Posting for posterity.
As suggested by #Steven Dee, I went to Pandoc.
I try to use a mature and tested tool whenever I can versus baking my own regex. Hand built regex's can be overly greedy, or not greedy enough, and they may not be sensitive to word boundaries and commas etc. Pandoc accounts for most this and more.
From the command line (the --smart parameter turns on smart quotes):
pandoc --smart --standalone -o output.html input.html
..and I know a command line script may or may not fit OP's requirement of using Javascript. (related: How to execute shell command in Javascript)
I'm sorry, I know the issue was addressed before, but I can't make any answer fit my problem...
I am writing a short script on google script, where I want to use the searchFile method on a folder, to look for a file whose name is stored in the string variable Name:
var theFileImLookingFor = theSourceFolder.searchFiles("title = '"+Name+"'").next();
This code works fine as long as the variable Name doesn't include quotation marks. Then, I'm stuck...
Please help me adapt my code :)
A simple but fragile solution could be to use backticks (`), usually found on the upper left of the keyboard on the same key as the tilde (~). These are sort of like quotation marks in javascript, but can also be used in ways that quotation marks can't.
Expect this solution to fail whenever the variable's value contains backticks.
Did you try to escape possible quotes ?
You probably could write a little function that take your variable "name" then escape possible quotes in it before returning it to searchFile. Or maybe with a simple "replace("'", "\'")"...
I am working on an Applescript script which executes some Javascript to add some HTML to a webpage I am viewing on my local machine. Applescript is reading the HTML file into a string and automatically escapes all the double quotes in the HTML like this: \"
But Javascript doesn't like the string with all the escaped double-quotes in it:
set programHTML to "\"Hi kid!\"" --This works!
set programHTML to "\"Hi \"kid!\"" --This doesn't!
I feel like I must be missing something very basic here. I scanned and skimmed many posts but have not seen anything addressing this specific problem.
[Adding this after what would have been a helpful comment had I been a bit more explicit]:
Nothing with more than the quotes on the end works when it gets to Javascript. This does not work:
set programHTML to "\"Howdy, \"kid!\", is your \"Mom\" home?\""
I should perhaps mention that this string is going into a line which looks something like this:
execute tab 1 of front window javascript "codeDIV.innerHTML = " & programHTML & ";"
Double Quotes must always be used in pair. that's why your second method does not works.
set programHTML to "\"Hi kid!\"" --This works!
-- Because it results in "Hi kid" - 2 double quotes
set programHTML to "\"Hi \"kid!\"" --This doesn't!
Because it results in "Hi "kid!" - 3 double quotes
Change the outer quotes to single quotes so they don't interfere with the inner double quotes. If you do this, you don't need to worry about escaping the double quotes at all.
//using the single quote in the beginning and end
console.log('"Howdy, "kid!", is your "mom" home?"');
reads as "Howdy, "kid!", is your "mom" home?"
I have been browsing lots of solutions, but somewhy haven't got anything to work.
I need to replace following string: "i:0#.w|dev\\tauri;" with "i:0#.w|dev\tauri;"
I have tried following JS codes to replace:
s.replace(/\\\\/g, "\\$1");
s.replace(/\\\\/g, "\\");
But have had no result. Yet following replaced my \\ with "
s.replace(/\\/g, "\"");
To be honset, then I am really confused behind this logic, it seems like there should be used \\\\ for double backshashed yet it seems to work with just \\ for two backshashes..
I need to do this for comparing if current Sharepoint user (i:0#.w|dev\tauri) is on the list.
Update:
Okay, after I used console.log();, I discovered something interesting.
Incode: var CurrentUser = "i:0#.w|dev\tauri"; and console.log(): i:0#.w|dev auri...
C# code is following:
SPWeb theSite = SPControl.GetContextWeb(Context);
SPUser theUser = theSite.CurrentUser;
return theUser.LoginName;
JavaScript strings need to be escaped so if you are getting a string literal with two back slashes, JavaScript interprets it as just one. In your string you are using to compare, you have \t, which is a tab character, when what you probably want is \\t. My guess is that wherever you are getting the current SharePoint user from, it is being properly escaped, but your compare list isn't.
Edit:
Or maybe the other way around. If you're using .NET 4+ JavaScriptStringEncode might be helpful. If you're still having problems it might help to show us how you are doing the comparison.
We can work with escape sequence in strings on JavaScript. For example, I can write \\ and it means \. But I don't want to use a escape sequence.
I know that on C# I can write #"My string" and I don't need to escape anything. Is there similar syntax in JavaScript?
No, there's not. However, there are RegExp literals:
/foo\s+bar/
There is no such syntax, but there is a work around:
var string = (<r><![CDATA[
Now you can put a whole lot of stuff here.
Including new lines, and all sorts of symbols: \ " '
]]></r>).toString();
Because it's so verbose it's only worth using this when you have something that would be otherwise unreadable (eg: a pretty long string with a bunch of characters that need escaping).