javascript - replace any of these characters with nothing: '' - Stack Overflow

somevar = ' 150,00 $';someothervar = '$25.0;I want to remove dollar signs, spaces, mas

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

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

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

So it looks like the ma 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?

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

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

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

So it looks like the ma 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?

Share Improve this question asked Nov 19, 2015 at 23:27 Doug FirDoug Fir 21.4k54 gold badges192 silver badges341 bronze badges 3
  • What is the expected output? 150,00 $ -> 150 or 15000? – Wiktor Stribiżew Commented Nov 19, 2015 at 23:30
  • are you pletely sure about dots and mas? – RobertoNovelo Commented Nov 19, 2015 at 23:30
  • /\D/g is the best way, but be careful, one day if your occasionally remove the decimals from your response... ;) – Roko C. Buljan Commented Nov 19, 2015 at 23:40
Add a ment  | 

2 Answers 2

Reset to default 2

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"

I would:

var somePriceString = "$$2.903.5,,,3787.3";

console.log(somePriceString.replace(/\D/g,''));

If I wanted to remove any non-digit character.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744975708a4604130.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信