2 // Copyright (c) 2007 James Newton-King
4 // Permission is hereby granted, free of charge, to any person
5 // obtaining a copy of this software and associated documentation
6 // files (the "Software"), to deal in the Software without
7 // restriction, including without limitation the rights to use,
8 // copy, modify, merge, publish, distribute, sublicense, and/or sell
9 // copies of the Software, and to permit persons to whom the
10 // Software is furnished to do so, subject to the following
13 // The above copyright notice and this permission notice shall be
14 // included in all copies or substantial portions of the Software.
16 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
18 // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
19 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
20 // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
21 // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
22 // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
23 // OTHER DEALINGS IN THE SOFTWARE.
27 using System.Collections;
28 using System.Globalization;
31 using System.Text.RegularExpressions;
32 using System.Collections.Generic;
34 namespace Newtonsoft.Json.Utilities
36 internal static class JavaScriptUtils
38 public static void WriteEscapedJavaScriptString(TextWriter writer, string value, char delimiter, bool appendDelimiters)
42 writer.Write(delimiter);
46 int lastWritePosition = 0;
50 for (int i = 0; i < value.Length; i++)
75 case '\u0085': // Next Line
76 escapedValue = @"\u0085";
78 case '\u2028': // Line Separator
79 escapedValue = @"\u2028";
81 case '\u2029': // Paragraph Separator
82 escapedValue = @"\u2029";
85 // only escape if this charater is being used as the delimiter
86 escapedValue = (delimiter == '\'') ? @"\'" : null;
89 // only escape if this charater is being used as the delimiter
90 escapedValue = (delimiter == '"') ? "\\\"" : null;
93 escapedValue = (c <= '\u001f') ? StringUtils.ToCharAsUnicode(c) : null;
97 if (escapedValue != null)
100 chars = value.ToCharArray();
102 // write skipped text
105 writer.Write(chars, lastWritePosition, skipped);
109 // write escaped value and note position
110 writer.Write(escapedValue);
111 lastWritePosition = i + 1;
119 // write any remaining skipped text
122 if (lastWritePosition == 0)
125 writer.Write(chars, lastWritePosition, skipped);
129 // trailing delimiter
130 if (appendDelimiters)
131 writer.Write(delimiter);
134 public static string ToEscapedJavaScriptString(string value)
136 return ToEscapedJavaScriptString(value, '"', true);
139 public static string ToEscapedJavaScriptString(string value, char delimiter, bool appendDelimiters)
141 using (StringWriter w = StringUtils.CreateStringWriter(StringUtils.GetLength(value) ?? 16))
143 WriteEscapedJavaScriptString(w, value, delimiter, appendDelimiters);