Reputation: 1143
In JavaScript, I need to replace all occurrences of the dot character (.) with the underscore character (_) if any EXCEPT the last one.
This expression replaces ALL occurrences of the dot character (.) including the last one with an underscore character (_) but I'm trying to figure out how to change this so it leaves the last (.) character alone.
str.replace(/\./g, '_');
Thanks !!
Steve
Upvotes: 1
Views: 758
Reputation: 174696
Use a negative lookahead,
> "12.34.56.78".replace(/\.(?![^.]*$)/g,"_")
'12_34_56.78'
> "12.34.56.78.".replace(/\.(?![^.]*$)/g,"_")
'12_34_56_78.'
Upvotes: 1
Reputation: 207501
The fun with look aheads.
"12.34.56.78".replace(/\.(?=[^.]*\.)/g,"_")
Upvotes: 5