Replace substring from string using index

If I have string as "TestDataData" I want to replace "Data" with "NewValue" so it should become "TestNewValueData", how do we achieve this ?

Note: I cant replace data directly otherwise last data will also updated..

1 answer

  • answered 2021-06-10 10:59 Kenny

    If you are able to use a RegEx, you could use the following:

    str.replace("Data.+", "NewValue")

    The .+ assures at least one more letter follows after "Data".

    Alternatively, you could check if the index of your needle is less than the length of the haystack minus the length of the needle.