i need a regex in c# that will escape double quotes inside string literal. so if i have this string: "How about "this" and how about "that"". i will be able to use it in javascript without errors. because i am writing this literal to the page as js var.
EDIT: i will try to explain more about the problem.
i writing messege to the page like this:
string UserMsg = GetMessageText(999);
StringBuilder script = new StringBuilder();
script.AppendFormat("var UserMsg =\"{0}\";{1}", UserMsg, Environment.NewLine);
ScriptManager.RegisterClientScriptBlock(this, GetType(), "scriptparams", script.ToString(),true);
now lets say messege 999 is this: "we found a "problem" in your details".
this is causing js errors.
You should not use regular expressions to escape your C# strings into a JavaScript friendly / safe format. Instead, assuming you are using .NET 4, you can use HttpUtility.JavaScriptStringEncode and it's overload to take care of both single and double quotes for you.
For example:
string UserMsg = GetMessageText(999);
StringBuilder script = new StringBuilder();
script.AppendFormat("var UserMsg =\"{0}\";{1}", HttpUtility.JavaScriptStringEncode(UserMsg), Environment.NewLine);
ScriptManager.RegisterClientScriptBlock(this, GetType(), "scriptparams", script.ToString(),true);
Would ouput the following with UserMsgset to "we found a "problem" in your details":
var UserMsg ="we found a \"problem\" in your details";
Assuming I understand you correctly, to escape a " in C# source code, you can do it like this:
"\""
or
#""""
Either of those literals defines a string containing single double quote character.
On the other hand perhaps you need to know how to escape the quote character in Javascript. That is done with \". You can use String.Replace() to effect that but you would be much better off with a proper HTML/JS emitter library.
See the Web Protection Library (also known as AntiXSS). That has a JavascriptEncode method to do this and other escapes.
Here is my suggestion for you:
var regex = new Regex("\"");
var result = regex.Replace(stringToReplace, "\\\"");
I believe something like this may work:
Regex.Replace(myString,'"',"");
I think your question has been answered already but if you still need the complete code.
below piece of javascript would work for you.
var s = "this is \"Hi \" ";
alert(s);
Praveen
Related
I am trying to add a new line Javascript alert message. I tried '\n' and 'Environment.NewLine'. I am getting Unterminated string constant error. Could you please let me know what could be the problem? I appreciate any help. I also tried \r\n.
string msg = "Your session will expire in 10 minutes. \n Please save your work to avoid this.";
if (!this.ClientScript.IsStartupScriptRegistered(ID))
this.ClientScript.RegisterStartupScript(GetType(), ID, String.Format("<script language=JavaScript>setTimeout(\'alert(\"{1}\");\',{0}*1000);</script>", sTime, msg));
I would suspect that you need to change your code to;
string msg = "Your session will expire in 10 minutes. \\n Please save your work to avoid this.";
And escape the \n otherwise your code outputted would actually include the line break rather than \n
Your output code would look like:
setTimeout('alert("Your Session....
Please save your work to ....");', 1000);
Rather than:
setTimeout('alert("Your Session....\n Please save your work to ....");', 1000);
I'm not sure, but I think that \n is escaped in the string.Format method, like \". Maybe you should use \\n instead.
Edited : and the first \ of \\n has been escaped when i posted that. xD
At first glance I would say the primary problem is that you're escaping the ' character around your alert. Since your string is defined by the double quotes, you don't need to escape this character.
add "#" at the beginning of your string - like this:
string msg = #"Your session ....";
The code looks fine, so I'm going to guess that you're using a message that itself has a ' quote in it, causing the JS syntax error. For inserting dynamic text into a Javascript code block, you really should use JSON to make your C# strings 'safe' for use in JS.
Consider JSON the go-to method for preventing the JS equivalent of SQL injection attacks.
Adding a # at the beginning should help.
I am using HighCharts and am generating script from C# and there's an unfortunate thing where they use inline functions for formatters and events. Unfortunately, I can't output JSON like that from any serializer I know of. In other words, they want something like this:
"labels":{"formatter": function() { return Highcharts.numberFormat(this.value, 0); }}
And with my serializers available to me, I can only get here:
"labels":{"formatter":"function() { return Highcharts.numberFormat(this.value, 0); }"}
These are used for click events as well as formatters, and I absolutely need them.
So I'm thinking regex, but it's been years and years and also I was never a regex wizard.
What kind of Regex replace can I use on the final serialized string to replace any quoted value that starts with function() with the unquoted version of itself? Also, the function itself may have " in it, in which case the quoted string might have \" in it, which would need to also be replaced back down to ".
I'm assuming I can use a variant of the first answer here:
Finding quoted strings with escaped quotes in C# using a regular expression
but I can't seem to make it happen. Please help me for the love of god.
I've put more sweat into this, and I've come up with
serialized = Regex.Replace(serialized, #"""function\(\)[^""\\]*(?:\\.[^""\\]*)*""", "function()$1");
However, my end result is always:
formatter:function()$1
This tells me I'm matching the proper stuff, but my capture isn't working right. Now I feel like I'm probably being an idiot with some C# specific regex situation.
Update: Yes, I was being an idiot. I didn't have a capture around what I really wanted.
`enter code here` serialized = Regex.Replace(serialized, #"""function\(\)([^""\\]*(?:\\.[^""\\]*)*)""", "function()$1");
that gets my match, but in a case like this:
"formatter":"function() { alert(\"hi!\"); return Highcharts.numberFormat(this.value, 0); }"
it returns:
"formatter":function() { alert(\"hi!\"); return Highcharts.numberFormat(this.value, 0); }
and I need to get those nasty backslashes out of there. Now I think I'm truly stuck.
Regexp for match
"function\(\) (?<code>.*)"
Replace expression
function() ${code}
Try this : http://regexr.com?30jpf
What it does :
Finds double quotes JUST before a function declaration and immediately after it.
Regex :
(")(?=function()).+(?<=\})(")
Replace groups 1 & 3 with nothing :
3 capturing groups:
group 1: (")
group 2: ()
group 3: (")
string serialized = JsonSerializer.Serialize(chartDefinition);
serialized = Regex.Replace(serialized, #"""function\(\)([^""\\]*(?:\\.[^""\\]*)*)""", "function()$1").Replace("\\\"", "\"");
I would like to do the following:
if (string.Contains("/"))
{
string.Replace("/", "\/"); //this isn't valid
}
I've tried
string.Replace("/", "\\/");
but this gives me what I started with. How can I do this?
Thanks
Strings are immutable, which means that any modification you do to a string results in a new one, you should assign the result of the Replace method:
if (myString.Contains("/"))
{
myString = myString.Replace("/", "\\/");
}
String.Replace returns the string with replacements made - it doesn't change the string itself. It can't; strings are immutable. You need something like:
text = text.Replace("/", "\\/");
(In future examples, it would be helpful if you could use valid variable names btw. It means that those wishing to respond with working code can use the same names as you've used.)
One way is to use a verbatim string literal
string.Replace("/", #"\");
If you have a string with a numerous double quotes,
in PHP you can do this:
file.WriteLine('<controls:FormField Name="Strasse" LabelText="Strasse">');
in C# you have to do this:
file.WriteLine("<controls:FormField Name=\"Strasse\" LabelText=\"Strasse\">");
Is there a way in C# to do what you can do above in PHP, something like the #"c:\temp" which you can do so that you don't need double slashes?
Thanks Fredrik, that makes even quotes and curly brackets in a String.Format fairly readable:
file.WriteLine(String.Format(#"<TextBox Text=""{{Binding {0}}}""
Style=""{{DynamicResource FormularFieldTextBox}}""/>", fieldName));
There are two ways to represent quotes in C# strings:
file.WriteLine("<controls:FormField Name=\"Strasse\" LabelText=\"Strasse\">");
file.WriteLine(#"<controls:FormField Name=""Strasse"" LabelText=""Strasse"">");
"<controls:FormField Name='Strasse' LabelText='Strasse'>".Replace("'", "\"")
Which isn't great, but about the only option.
Or #"""" insted of \" you can use ""
I would recommend avoiding some bizarre way like this:
const char doubleQuote = '"';
Console.WriteLine("<controls:FormField Name={0}Strasse{0} LabelText={0}Strasse{0}>", doubleQuote);
I would recommend using a resource file to store the string constants.
This increases elegance and code readability.
Also, quotes and special characters can be displayed without messing around with too many escape sequences.
You can create a resource file entry like,
String Name(Key) => FormFieldControl
Value => <controls:FormField Name="{0}" LabelText="{1}">
This can be used in code like
const string fieldName = "Strasse";
Console.WriteLine(ResourceFile.FormFieldControl, fieldName, fieldName);
I am consuming the Twitter API and want to convert all URLs to hyperlinks.
What is the most effective way you've come up with to do this?
from
string myString = "This is my tweet check it out http://tinyurl.com/blah";
to
This is my tweet check it out http://tinyurl.com/>blah
Regular expressions are probably your friend for this kind of task:
Regex r = new Regex(#"(https?://[^\s]+)");
myString = r.Replace(myString, "$1");
The regular expression for matching URLs might need a bit of work.
I did this exact same thing with jquery consuming the JSON API here is the linkify function:
String.prototype.linkify = function() {
return this.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/, function(m) {
return m.link(m);
});
};
This is actually an ugly problem. URLs can contain (and end with) punctuation, so it can be difficult to determine where a URL actually ends, when it's embedded in normal text. For example:
http://example.com/.
is a valid URL, but it could just as easily be the end of a sentence:
I buy all my witty T-shirts from http://example.com/.
You can't simply parse until a space is found, because then you'll keep the period as part of the URL. You also can't simply parse until a period or a space is found, because periods are extremely common in URLs.
Yes, regex is your friend here, but constructing the appropriate regex is the hard part.
Check out this as well: Expanding URLs with Regex in .NET.
You can add some more control on this by using MatchEvaluator delegate function with regular expression:
suppose i have this string:
find more on http://www.stackoverflow.com
now try this code
private void ModifyString()
{
string input = "find more on http://www.authorcode.com ";
Regex regx = new Regex(#"\b((http|https|ftp|mailto)://)?(www.)+[\w-]+(/[\w- ./?%&=]*)?");
string result = regx.Replace(input, new MatchEvaluator(ReplaceURl));
}
static string ReplaceURl(Match m)
{
string x = m.ToString();
x = "< a href=\"" + x + "\">" + x + "</a>";
return x;
}
/cheer for RedWolves
from: this.replace(/[A-Za-z]+://[A-Za-z0-9-]+.[A-Za-z0-9-:%&\?/.=]+/, function(m){...
see: /[A-Za-z]+://[A-Za-z0-9-]+.[A-Za-z0-9-:%&\?/.=]+/
There's the code for the addresses "anyprotocol"://"anysubdomain/domain"."anydomainextension and address",
and it's a perfect example for other uses of string manipulation. you can slice and dice at will with .replace and insert proper "a href"s where needed.
I used jQuery to change the attributes of these links to "target=_blank" easily in my content-loading logic even though the .link method doesn't let you customize them.
I personally love tacking on a custom method to the string object for on the fly string-filtering (the String.prototype.linkify declaration), but I'm not sure how that would play out in a large-scale environment where you'd have to organize 10+ custom linkify-like functions. I think you'd definitely have to do something else with your code structure at that point.
Maybe a vet will stumble along here and enlighten us.