Dawid77 Dawid77 - 1 month ago 6
Javascript Question

How to remove all letters from string

How can I remove only letters from string ?
For example, I have this text 345-d34 XX

And I want to get 345-34

I tried this code:

replace(/\D/g, '')


But it's now working correct because I get only numbers without -

Answer

If you really only want to remove (latin) letters from your string:

replace(/[a-z]/gi, '') 

If you want to keep only digits and hyphens:

replace(/[^\d-]/g, '')

NB: If you plan to use the second solution and want to add other characters you want to keep, make sure to keep the hyphen last in the class, otherwise it changes meaning and will act like a range.