C # bij Jquery function replacement not working without knowing how to troubleshoot

I am trying to replace ASP.NET (C #) server method with javascript / Jquery method. I'm new to JQuery, but it went well until I started with regex.

my code is 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();
       throw new Exception("Postcode incorrect");


in JQuery I'm only focused to replace for now manually by entering the correct lines.

I created a function like:

function FormatDutchPostalCode() {
   var postcode = $("#Text1").val();
   postcode = postcode.replace(/(^[1-9]\d{3})( ?)([a-zA-Z]{2}$)/, $1$3);


I am getting the value from the textbox how good is that. But when replaced, it seems like browsers are breaking out of function (tested in IE9 and FF10.0.1)

What am I doing wrong and can I eliminate JQuery / Javascript. I have seen how firebug could set breakpoints, but I cannot find any errors (and if so).


source to share

2 answers

Here is a port of your C # function to JS. It uses IIFE to cache the regex without polluting the current execution scope.


var FormatDutchPostalCode = (function() {
    var reg = /^([1-9]\d{3})\s?([a-z]{2})$/i;
    return function(){
        var postcode = $.trim($("#Text1").val());
        if (postcode && postcode.match(reg) )
            return postcode.replace(reg, "$1$2").toUpperCase();
            throw new Error("Postcode incorrect");




For a replacement pattern, you need to use '$1$3'

or /$1$3/

. Currently, you have placed the replacement pattern without using it as a string or regex pattern.

Check out the jsFiddle for a link showing a working solution.

You can also simplify your template by removing the capture group for extra space, then you can do the replacement using the existing capture groups:

  • Pattern: /^([1-9]\d{3}) ?([a-zA-Z]{2})$/

  • Replacement: '$1$2'

    (there are only 2 groups)

To use Firebug or developer tools, you can launch the tool with a key F12. You can test your replacement directly in the console window, or debug the script from the script tab (select the appropriate JavaScript file) and place a breakpoint on the line of interest by right-clicking and adding it, or by clicking on the line number on the left.

Check out this article for more details: Debugging JavaScript for Beginners .



All Articles