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.
2 Answers
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."
2 Comments
user1058913
But the regex is not working if the string is like this "Device.test.point.1.params.enabled"
Amadan
Oh, didn't think that's what you want (because your original code also doesn't do the right thing in this case). In that case, use
/\d+(?=\.\D+$)/, "replace all the digits that are followed by a period and some non-digits before the end of string with an asterisk".