To keep only alphabets in a string in JavaScript, you can use a regular expression with the replace() method to remove non-alphabetic characters.
In this example,
str1
with a value of "Hello123 World"
.replace()
method with a regular expression /[^a-zA-Z]/g
to replace non-alphabetic characters with an empty string globally.str1
to the console.let str1 = "Hello123 World";
str1 = str1.replace(/[^a-zA-Z]/g, "");
console.log("Modified string: " + str1);
Modified string: HelloWorld
In this example,
str2
with a value of "apple@banana"
.replace()
method with a regular expression /[^a-zA-Z]/g
to replace non-alphabetic characters with an empty string globally.str2
to the console.let str2 = "apple@banana";
str2 = str2.replace(/[^a-zA-Z]/g, "");
console.log("Modified string: " + str2);
Modified string: applebanana
In this tutorial, we learned How to keep only Alphabets in a String in JavaScript language with well detailed examples.