I’m trying to replace an ASP.NET (C#) server-sided method by an javascript/Jquery method. I’m fairly new to Jquery but all went well until I began with regular expressions.
my code in ASP.NET C#
if ((Regex.Match(postcode.Trim(), @"^[1-9]\d{3} ?[a-zA-Z]{2}$")).Success)
{
return Regex.Replace(postcode.Trim(), @"(^[1-9]\d{3})( ?)([a-zA-Z]{2}$)", "$1$3").ToUpper();
}
else
{
throw new Exception("Postcode incorrect");
}
in Jquery I’m only focussing to replace for the moment by manually input the right strings.
I’ve created a function like:
function FormatDutchPostalCode() {
var postcode = $("#Text1").val();
postcode = postcode.replace(/(^[1-9]\d{3})( ?)([a-zA-Z]{2}$)/, $1$3);
$("#Text1").val(postcode);
}
I’m getting the value from the textbox, so far so good. But when replacing it seems the browsers exits the function (tested in IE9 and FF10.0.1)
What I’m i doing wrong and is it possible to troubleshoot Jquery/Javascript. I’ve seen firebug could set breakpoints but I can’t find if (and if so which) errors occur.
Here is a port of your C# function to JS. It uses an IIFE in order to cache the regex without polluting the current execution scope.
jsFiddle