Reputation: 321
I have a string like "Test.1.Value.2.Configuration.3.Enable" , in which i want to replace only the last occurrence of the number '3' to '*'. the number may be any valid integer. Right row i did it by splitting the value to array and replacing array length-2 nd value to * and rejoining it. Would like to know if we can do it by using regular expressions.
Upvotes: 0
Views: 531
Reputation: 832
const newStr = str.split(".").map((e, i, arr) => i === arr.length - 2 ? "*" : e).join(".");
Upvotes: 0
Reputation: 198526
Yes, easily:
str = "Test.1.Value.2.Configuration.3.Enable";
newstr = str.replace(/\d+(?=\.[^.]+$)/, '*')
console.log(newstr)
"Replace all the digits that are followed by a period and some non-periods before the end of the string with an asterisk."
Upvotes: 3