javascript regex replace date pattern found with a different string

I’m trying to find a date pattern in some text fields and replace some of the text with a different date pattern if found, but I’m not too good on the regex stuff and need a bit of help.

Here’s what the text field data looks like coming in:

"Credit Rent from 03-01-2021 to 03-31-2021 for 31 days at $123.00"

I’m using a kendo slider to change the date span to 02-22-2021 to 02-28-2021

I’m trying to replace 03-01-2021 to 03-31-2021 to be 02-22-2021 to 02-28-2021 so the final description text will read Credit Rent from 02-22-2021 to 02-28-2021 for 31 days at $123.00 and then I’ll put that string back into the original text value.

I don’t think my regex below is picking up the date pattern match.

Here’s my javascript…I’m using jquery to loop through the input elements:

var pattern_to_match_2 = "/^(\d{1,2})-(\d{1,2})-(\d{4}) to (\d{1,2})-(\d{1,2})-(\d{4})/g"; // mm-dd-yyyy
var replace_with_2 = "02-22-2021 to 02-28-2021";


$(".item_detail_record ").each(function(e){
    var description = $(this).find("#description").val(); //Returns: "Credit Rent from 03-01-2021 to 03-31-2021 for 31 days at $123.00"

    var new_value = description.replace(pattern_to_match_2, replace_with_2);
    $(this).find("#description").val(new_value );

});

Any help or direction will be appreciated. Thanks

80 thoughts on “javascript regex replace date pattern found with a different string”

  1. Hello there, I discovered your web site by the use of Google while searching for a related subject, your
    website came up, it appears to be like great. I have bookmarked it in my google bookmarks.

    Hi there, simply changed into aware of your weblog thru Google,
    and found that it’s truly informative. I’m
    going to watch out for brussels. I will appreciate in case you proceed this in future.
    Lots of other people can be benefited out of your writing.
    Cheers! http://herreramedical.org/viagra

    Reply

Leave a Comment