How to Remove Numbers from a String in JavaScript

Let's say you are tasked with removing numbers from a string in JavaScript. Here are the steps that can help you complete the task.

First, let us convert the string to an array

const str = "Si0m1123on994";
const strAry = str.split('');

Next, we have to Iterate over the array using map() method.

let strRes = strAry.map(function(res){

})

Now we have to check if the current element is a number or not using isNaN().

Using the function isNaN(), we are able to return only elements that are not integers.

let strRes = strAry.map(function(res){
return( (isNaN(res)) ? res : null );
})

Then we convert the result back to string.

let result = strRes.join('');
console.log(result);

Testing out our code

I will use the string above to test my code

Here's an image with the printed value.

 

It works!

Thank you for reading!


Simon Ugorji

16 Blog Beiträge

Kommentare