0

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 2

3

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."

Sign up to request clarification or add additional context in comments.

2 Comments

But the regex is not working if the string is like this "Device.test.point.1.params.enabled"
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".
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.