OneCompiler

[Javascript] How do I remove all the alphabets leaving numbers from a given string?

I want to remove all the alphabets from a given string leaving only numbers behind. How can I do that in Javascript?

1 Answer

4 years ago by

Use regex to remove all the alphabets from a given string as shown below

let str = "This is a test message with id 12345";


// to remove all the alphabets
console.log(str.replace(/[A-Za-z\s+]/g, '')) // Outputs "12345"

// to remove all the numbers
console.log(str.replace(/\d/g, '')) // Outputs "This is a test message with id"

Run here https://onecompiler.com/javascript/3xns3vzfb

4 years ago by Meera