0
$('.hourfield').focusout(function() {

    var h;
    var m;
    var timeStr = "";
    var time = "";
    var newFormat = "";

    timeStr = $(this).val();

    //Here I would like to remove all characters which isn't numbers
    timeStr = timeStr.replace("/[^0-9\.]+/g","");

    if(timeStr > 0) {

        h = timeStr.substr(0,2);
        m = timeStr.substr(2,2);

        newFormat = h+':'+m;

        //Add new values
        $(this).val(newFormat);
    }

});

URL to website

4
  • 1
    What is the issue here? Commented Mar 19, 2013 at 14:39
  • 1
    The regex you wrote, "/[^0-9\.]+/g". You wanted it to be a regex, but you ended up with a string. Lose the quotes and you'll be fine. Commented Mar 19, 2013 at 14:41
  • The replace() function doesn't seem to remove the characters if you for example insert "10.00" in the input field. I would like it to remove the dot before reformatting it with the "10:00". Commented Mar 19, 2013 at 14:41
  • I've just updated the the code with your suggestion and if you write "10.00" and then click somewhere else you get "10:.0". It should generate "10:00". Commented Mar 19, 2013 at 14:47

2 Answers 2

3

You've specified a string to replace by enclosing the regex in quotes. Remove the quotes to specify a Regex.

timeStr = timeStr.replace(/[^0-9\.]+/g,"");
Sign up to request clarification or add additional context in comments.

Comments

0
$('.hourfield').focusout(function() {

    var h;
    var m;
    var timeStr = "";
    var CleanTimeStr = "";
    var newFormat = "";

    timeStr = $(this).val();

I did some minor changes to the replace() rule and just removed the "dots" which was the main purpose

    CleanTimeStr = timeStr.replace(/[.]+/g,"");

    if(CleanTimeStr > 0) {

        h = CleanTimeStr.substr(0,2);
        m = CleanTimeStr.substr(2,2);

        newFormat = h+':'+m;

        //Add new values
        $(this).val(newFormat);
    }
});

So now it works fine, thanks!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.