user1058913
user1058913

Reputation: 321

Replace last occurrence of number with * using regular expression in Javascript

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

Answers (2)

Misha Tavkhelidze
Misha Tavkhelidze

Reputation: 832

const newStr = str.split(".").map((e, i, arr) => i === arr.length - 2 ? "*" : e).join(".");

Upvotes: 0

Amadan
Amadan

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

Related Questions