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

1 thought on “javascript regex replace date pattern found with a different string”

  1. You’re regex looks good if you do two things:

    1. Make it a RegExp – right now you’re trying to literally match the string "/^(\d{1,2})-(\d{1,2})-(\d{4}) to (\d{1,2})-(\d{1,2})-(\d{4})/g" which of course doesn’t appear in your input.

    2. Remove the ‘Start of string anchor’ ^ because what this is saying in essence is "from the start of the string, start looking for these numbers"

    The first line should now be:

    var pattern_to_match_2 = new RegExp(/(\d{1,2})-(\d{1,2})-(\d{4}) to (\d{1,2})-(\d{1,2})-(\d{4})/gi);

    var pattern_to_match_2 = new RegExp(/(\d{1,2})-(\d{1,2})-(\d{4}) to (\d{1,2})-(\d{1,2})-(\d{4})/g);
    var replace_with_2 = "02-22-2021 to 02-28-2021";
    
    
    $(".item_detail_record ").each(function(e){
        var description = $(this).find("#description").val();
        console.log(description)
        var new_value = description.replace(pattern_to_match_2, replace_with_2);
        console.log(new_value)
        $(this).find("#description").val(new_value );
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    <div class="item_detail_record">
      <input id="description" value="Credit Rent from 03-01-2021 to 03-31-2021 for 31 days at $123.00" />
    </div>
    Reply

Leave a Comment