Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replace any of these characters with nothing: ''

somevar = ' 150,00 $';
someothervar = '$25.0;

I want to remove dollar signs, spaces, commas or dots.

Tried somevar.replace(/('$'|' '|,|\.)/g,''); returned 15000 $ (leading space).

So it looks like the comma is being removed but not everything else?

I could go like this:

somevar.replace(/\$/g,'').replace(/ /g,'').replace(/,/g,'')

But surely there's a more 'elegant' way?

like image 229
Doug Fir Avatar asked Nov 02 '25 01:11

Doug Fir


1 Answers

You could use /[$,.\s]/g:

' 150,00 $'.replace(/[$,.\s]/g, '');
// "15000"

'$25.0'.replace(/[$,.\s]/g, '');
// "250"

Your regular expression wasn't working because you needed to escape the $ character, and remove the single quotes. You could have used: /\$| |,|\./g.

Alternatively, you could also just replace all non-digit character using /\D/g:

' 150,00 $'.replace(/\D/g, '');
// "15000"

'$25.0'.replace(/\D/g, '');
// "250"
like image 86
Josh Crozier Avatar answered Nov 03 '25 15:11

Josh Crozier