Uthistran Selvaraj
Uthistran Selvaraj

Reputation: 1371

string with "$" not giving expected output in Javascript

I have a string "$$$$$1.00" Need to replace all '$' with empty string. I don't know the exact number of '$' as I fetch it from server.

I tried using

"$$$$$1.00".replace(/$/g, "")

which is not working out.

I know I can run through the loop and remove it. Is there any way to do that. Also, why it is not working ?

It is working in this case

I have added the JSfiddle link for the simple executable JSFiddle

Upvotes: 0

Views: 41

Answers (2)

hawkstrider
hawkstrider

Reputation: 4341

Since you want to replace them all, you should use /\$+/to match 1 or more of them and make sure you escape the $ with \$ to match the literal string "$"

"$$$$$1.00".replace(/\$+/, "")

Upvotes: 0

seantunwin
seantunwin

Reputation: 1768

You need to escape the dollar sign ($) in the RegExp as this means the end of the string in RegExp world.

Refactor to:

"$$$$$1.00".replace(/\$/g, "")

Upvotes: 1

Related Questions