user815460
user815460

Reputation: 1143

Replace all occurrences of the dot character with an underscore character in javascript

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

Answers (2)

Avinash Raj
Avinash Raj

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

epascarello
epascarello

Reputation: 207501

The fun with look aheads.

"12.34.56.78".replace(/\.(?=[^.]*\.)/g,"_")

Upvotes: 5

Related Questions