I have a question that I feel will be simple to answer: I have the code
function ApplicantNameMatchedInitialPayment() {
var applicantName = '<%= ViewData["ApplicantName"] %>';
var fullName = applicantName.split(' ');
if (fullName.length == 2)
{
var firstName = fullName[0].toLowerCase();
var lastName = fullName[1].toLowerCase();
var nameOnCard = $("#name-on-card").val().toLowerCase();
if(nameOnCard.includes(firstName) & (nameOnCard.includes(lastName)))
{
return true;
}
}
return false;
}
I am trying to handle a case where my user enters their name with an apostrophe. When the ViewData Object is filled during live execution, the customer's name will show up in the 'applicantName' variable. The problem is that if I enter a name like "De'Leon", a JS error is thrown in the console because of an incorrect escape sequence.. and the string will not be read correctly. I want to take any string that is passed in from my C# Viewdata object and handle the apostrophes dynamically so that no errors are thrown and so that my javascript understands that everything should just be one string. A little help with the string formatting and escape character?
If you want to just escape apostrophes in JavaScript you could try to simply replace them with \’:
s = s.replace("'", "\'");
It won’t affect your further work with this string so if you write it to the console it will output a result without backslash:
var s = "De'Leon";
s = s.replace("'", "\'");
console.log(s); // > De'Leon
If you're using .NET version 4 or later, you can use HttpUtility.JavaScriptStringEncode.
Related
In my code I am saving the Regular Expression for validating the UK Mobile number i.e. "^(+44\s?7\d{3}|(?07\d{3})?)\s?\d{3}\s?\d{3}$" in to the Sql server database.
On retrieving the expression to validate the mobile number the "\" will be replaced with the "\", this gives a serious issue as on checking it says the mobile number is invalid even though its valid. I tried to replace the double slash with single or even by replacing the slash with some special characters in the database.
If I give the regex expression statically it works fine for me:
C# Code:
bool isPhoneNumber = Regex.IsMatch(sColumnValue, #"^(\+44\s?7\d{3}|\(?07\d{3}\)?)\s?\d{3}\s?\d{3}$");
if (isPhoneNumber == true)
{
//Do something...
}
else
{
//Do something...
}
But replaces when I get the Regex string stored in database.I have replaced "\" with special characters in database "###" i.e.
"^(###+44###s?7###d{3}|###(?07###d{3}###)?)###s?###d{3}###s?###d{3}$"
C# code:
string sRegxE = Context.Fields.Where(s => s.Name == sColumnName).Select(s => s.ExpressionValue).FirstOrDefault();
string sExpression= sRegxE.Replace(#"###", #"\");
if (isPhoneNumber == true)
{
//Do something...
}
else
{
//Do something...
}
This doesn't work for me and I am getting the double slash instead of single slash with produces serious effect on Regex validation.
Can anybody help me to prevent the replacing of single backslash in C#, Cheers!!
You can simply use .Replace() function like below :-
string temp = "^(###+44###s?7###d{3}|###(?07###d{3}###)?)###s?###d{3}###s?###d{3}$";
temp = temp.Replace("^(###+44###s?7###d{3}|###(?07###d{3}###)?)###s?###d{3}###s?###d{3}$", "\");
Or
temp = temp.Replace("^(###+44###s?7###d{3}|###(?07###d{3}###)?)###s?###d{3}###s?###d{3}$", "\\");
And can use it like :-
bool isPhoneNumber = Regex.IsMatch(sColumnValue, temp);
if (isPhoneNumber == true)
{
//Do something...
}
else
{
//Do something...
}
Edited:-
You can also use Regex.Unescape()
Have a look on below link for more details :-
Many regular expressions contain escaped characters. Sometimes you want to unescape these characters to get their original representation.
https://www.dotnetperls.com/unescape
I tried the following code and it worked
string data = "+447712345678";
string pattern = #"^(###+44###s?7###d{3}|###(?07###d{3}###)?)###s?###d{3}###s?###d{3}$";
pattern = pattern.Replace(#"###", #"\");
if (Regex.IsMatch(data, pattern))
{
//Do something...
}
else
{
//Do something...
}
Finally I solved it.
What I am doing here is instead of using "Regex.IsMatch()" directly,I created a Regex object and passing the dynamic value from the Sql server database i.e. ^(+44\s?7\d{3}|(?07\d{3})?)\s?\d{3}\s?\d{3}$, then check whether the input matches.
Code:
string sRegxE =dbContext.GetFields.Where(s => s.Name == sColumnName).Select(s => s.ExpressionValue).FirstOrDefault();
Regex RgxM = new Regex("" + sRegxE + "");
Match isPhoneNumber = RgxM.Match(sColumnValue);
if (isPhoneNumber.Success)
{
//Do somthing...
}
Reference:
Capture variable string in a regular expression?
This might be a problem with Session and not ToString(), I'm not sure.
I have two .aspx pages and I want to pass an IP address from a datatable from one page to the other. When I do this, spaces get added that I don't want. The simple version of the code is this:
first .aspx page
int num = DropDownList1.SelectedIndex;
DataView tempDV = SqlDataSource2.Select(DataSourceSelectArguments.Empty) as DataView;
Session["camera"] = tempDV.Table.Rows[num].ItemArray[2];
Response.Redirect("test.aspx");
test.aspx page
string ipCamAdd = Session["camera"].ToString();
TextBox1.Text = "http://" + ipCamAdd + "/jpg/image.jpg?resolution=320x240";
what I want to print is
http ://ipadd/jpg/image.jpg?resolution=320x240
but what prints out is
http//ipaddress /jpg/image.jpg?resolution=320x240
how can I fix this?
Also, I asked this question hoping someone could tell me why this is happening as well. Sorry for the mistake.
Try this:
string ipCamAdd = Session["camera"].Trim().ToString();
For the valid concern, Session["camera"] could be null, add function such as the following to your code
static string ToSafeString(string theVal)
{
string theAns;
theAns = (theVal==null ? "" : theVal);
return theAns;
}
Then use:
string ipCamAdd = Session["camera"].ToSafeString().Trim();
You can use string.Replace if you just want to get rid of the spaces:
TextBox1.Text = "http://" + (ipCamAdd ?? "").Replace(" ", "") + "/jpg/image.jpg?resolution=320x240";
Trim the result before setting to session.
Session["camera"] = tempDV.Table.Rows[num].ItemArray[2].Trim();
Seems In SQL your data type is char(*) if you convert the data type to varchar and re enter data, you wont get any additional spaces
I have a function in C# that finds the name of a function in a source file such as
function void MyFunc
I'm trying to create a substring that starts after "void " and I need to find the length of the name of the function. There will always be a space or a newline after the function name.
module MyApplication
[EntryPoint]
function void main
write("a string")
endfunction
endmodule
You can use LastIndexOf to find the last space, and grab the part of the string following to get the function name. Then use the Length property to get the length of the code:
var s = "function void MyFunc "; // example string
var s2 = s.Trim(); // remove any extra spaces at the end
var funcName = s2.Substring(s2.LastIndexOf(' ') + 1); // 'MyFunc'
var length = funcName.Length; // 6
Demo: http://www.ideone.com/64IYz
I assume that the function name might have other stuff after it, like a parameter list.
What you want to do is look for the word "void", go past it, find the first non-space character (which is the beginning of the function name), and then go to the next space or end of line.
You can use:
const string LookFor = "void "; // note space at end.
string GetFunctionName(string line)
{
int voidPos = line.IndexOf(LookFor);
if (voidPos == -1)
return null;
int functionStart = voidPos + LookFor.Length;
int spacePos = line.IndexOf(' ', functionStart);
if (spacePos == -1)
spacePos = line.Length;
return line.Substring(functionStart, spacePos - functionStart);
}
That's "crying for using regex". Try this:
Regex regex = new Regex("(function void ){1,1}(?<functionName>^\w*)");
Sprache can do this, but you'd need to write a grammar for the whole file, as it doesn't implement "searching" for a match.
Something along these lines would parse just the function declaration - as noted above, to make your scenario work you need to add rules for modules and so on.
var identifier = (from first in Parse.Letter
from rest in Parse.LetterOrDigit.Many().Text()
select first + rest).Token();
var returnType = Parse.String("void").Or(Parse.String("int")).Token();
var functionKeyword = Parse.String("function").Token();
var endFunctionKeyword = Parse.String("endfunction").Token();
var function = from fk in functionKeyword
from rt in returnType
from functionName in identifier
from body in Parse.AnyChar.Until(endFunctionKeyword)
select functionName;
var name = function.Parse("function void main write(\"a string\") endfunction");
The variable name above will contain the string "main" (unless I've made some typos :))
Sprache is a bit more powerful than regular expressions, but doesn't require any special build-time processing. There are some tutorials on this approach linked from the Sprache homepage.
I have a string and need to replace some content based on certain substrings appearing in the string. e.g. a sample string might be
(it.FirstField = "fred" AND it.SecondField = True AND it.ThirdField = False AND it.FifthField = True)
and I want to transform it to:
(it.FirstField = "fred" AND it.SecondField = 'Y' AND it.ThirdField = 'N' AND it.FifthField = True)
i.e. if the substring appears in the string, I want to change the True to 'Y' and the False to 'N', but leave any other True/False values intact.
I have an array of substrings to look for:
string[] booleanFields = { "SecondField", "ThirdField", "FourthField" };
I can use something like if (booleanFields.Any(s => inputString.Contains(s))) to find out if the string contains any of the keywords, but what's the best way to perform the replacement?
Thanks.
In the words of clipit - it looks like you are trying to parse SQL, would you like some help with that?
You can try and do this via string manipulation, but you are going to run into problems - think about what would happen if you replaced "fred" with something else, perhaps:
(it.FirstField = "it.SecondField = True" AND it.SecondField = True)
I'm loathed to recommend it (because it's probably quite difficult), but the correct way to do this is to parse the SQL and manipulate the parsed expression - see Parsing SQL code in C# for what looks like an approach that could make this relatively straightfoward.
It's probably not the best answer due to the two very similar lines (one for true/one for false), but this works and is fairly neat for a Regex (with .Dump() ready for LINQPad paste).
It does however assume that you want to replace every ".FieldName = True" within your content (which will include cases where this format is enclosed in quotes as a string value).
void Main()
{
List<string> booleanFields = new List<string> { "SecondField", "ThirdField", "FourthField" };
string s = #"(it.FirstField = ""fred"" AND it.SecondField = True AND it.ThirdField = False AND it.FifthField = True)";
booleanFields.ForEach(bf => s = Regex.Replace(s, String.Format(#"[.]{0}[ ]*=[ ]*True", bf), String.Format(".{0} = 'Y'", bf)));
booleanFields.ForEach(bf => s = Regex.Replace(s, String.Format(#"[.]{0}[ ]*=[ ]*False", bf), String.Format(".{0} = 'N'", bf)));
s.Dump();
}
I am reading from history, and I want that when i come across a google query, I can extract the query string. I am not using request or httputility since i am simply parsing a string. however, when i come across URLs like this, my program fails to parse it properly:
http://www.google.com.mt/search?client=firefox-a&rls=org.mozilla%3Aen-US%3Aofficial&channel=s&hl=mt&source=hp&biw=986&bih=663&q=hotmail&meta=&btnG=Fittex+bil-Google
what i was trying to do is get the index of q= and the index of & and take the words in between but in this case the index of & will be smaller than q= and it will give me errors.
any suggestions?
thanks for your answers, all seem good :) p.s. i couldn't use httputility, not I don't want to. when i add a reference to system.web, httputility isn't included! it's only included in an asp.net application. Thanks again
It's not clear why you don't want to use HttpUtility. You could always add a reference to System.Web and use it:
var parsedQuery = HttpUtility.ParseQueryString(input);
Console.WriteLine(parsedQuery["q"]);
If that's not an option then perhaps this approach will help:
var query = input.Split('&')
.Single(s => s.StartsWith("q="))
.Substring(2);
Console.WriteLine(query);
It splits on & and looks for the single split result that begins with "q=" and takes the substring at position 2 to return everything after the = sign. The assumption is that there will be a single match, which seems reasonable for this case, otherwise an exception will be thrown. If that's not the case then replace Single with Where, loop over the results and perform the same substring operation in the loop.
EDIT: to cover the scenario mentioned in the comments this updated version can be used:
int index = input.IndexOf('?');
var query = input.Substring(index + 1)
.Split('&')
.SingleOrDefault(s => s.StartsWith("q="));
if (query != null)
Console.WriteLine(query.Substring(2));
If you don't want to use System.Web.HttpUtility (thus be able to use the client profile), you can still use Mono HttpUtility.cs which is only an independent .cs file that you can embed in your application. Then you can simply use the ParseQueryString method inside the class to parse the query string properly.
here is the solution -
string GetQueryString(string url, string key)
{
string query_string = string.Empty;
var uri = new Uri(url);
var newQueryString = HttpUtility.ParseQueryString(uri.Query);
query_string = newQueryString[key].ToString();
return query_string;
}
Why don't you create a code which returns the string from the q= onwards till the next &?
For example:
string s = historyString.Substring(url.IndexOf("q="));
int newIndex = s.IndexOf("&");
string newString = s.Substring(0, newIndex);
Cheers
Use the tools available:
String UrlStr = "http://www.google.com.mt/search?client=firefox-a&rls=org.mozilla%3Aen-US%3Aofficial&channel=s&hl=mt&source=hp&biw=986&bih=663&q=hotmail&meta=&btnG=Fittex+bil-Google";
NameValueCollection Items = HttpUtility.ParseQueryString(UrlStr);
String QValue = Items["q"];
If you really need to do the parsing yourself, and are only interested in the value for 'q' then the following would work:
string url = #"http://www.google.com.mt/search?" +
"client=firefoxa&rls=org.mozilla%3Aen-" +
"US%3Aofficial&channel=s&hl=mt&source=hp&" +
"biw=986&bih=663&q=hotmail&meta=&btnG=Fittex+bil-Google";
int question = url.IndexOf("?");
if(question>-1)
{
int qindex = url.IndexOf("q=", question);
if (qindex > -1)
{
int ampersand = url.IndexOf('&', qindex);
string token = null;
if (ampersand > -1)
token = url.Substring(qindex+2, ampersand - qindex - 2);
else
token = url.Substring(qindex+2);
Console.WriteLine(token);
}
}
But do try to look at using a proper URL parser, it will save you a lot of hassle in the future.
(amended this question to include a check for the '?' token, and support 'q' values at the end of the query string (without the '&' at the end) )
And that's why you should use Uri and HttpUtility.ParseQueryString.
HttpUtility is fine for the .Net Framework. However that class is not available for WinRT apps. If you want to get the parameters from a url in a Windows Store App you need to use WwwFromUrlDecoder. You create an object from this class with the query string you want to get the parameters from, the object has an enumerator and supports also lambda expressions.
Here's an example
var stringUrl = "http://localhost/?name=Jonathan&lastName=Morales";
var decoder = new WwwFormUrlDecoder(stringUrl);
//Using GetFirstByName method
string nameValue = decoder.GetFirstByName("name");
//nameValue has "Jonathan"
//Using Lambda Expressions
var parameter = decoder.FirstOrDefault(p => p.Name.Contains("last")); //IWwwFormUrlDecoderEntry variable type
string parameterName = parameter.Name; //lastName
string parameterValue = parameter.Value; //Morales
You can also see http://www.dzhang.com/blog/2012/08/21/parsing-uri-query-strings-in-windows-8-metro-style-apps