I was given this string:
var myMessage = "Learning is fun!"
This is how I attempted to create an array listing only the letters (without the spaces and "!").
var myMessage = "Learning is fun!";
var arr1 = myMessage.split("");
function onlyLetters(array){
let arr2 = []
for(let i = 0; i < array.length; i++){
if(array[i] === "a" || "b" || "c" || "d" || "e"
|| "f" || "g" || "h" || "i" || "j" || "k" || "l"
|| "m" || "n" || "o" || "p" || "q" || "r" || "s"
|| "t" || "u" || "v" || "w" || "x" || "y" || "z"){
arr2.push(array[i])
}
}
return arr2
}
console.log(onlyLetters(myMessage))
What am I doing wrong? Also, is there a shorthand for listing letters "a" through "z"?
A simple way may be to use Regex like so
let message = "Learning is fun!";
let onlyLettersArray = message.split('').filter(char => /[a-zA-Z]/.test(char));
console.log(onlyLettersArray)
.filter takes an array and runs a function on the elements, which returns true or false. The item is removed if it returns false. The regex checks if the character is within the range a-z or A-Z
Another way is to filter the char and then split it like so
let message = "Learning is fun!";
let onlyLettersArray = message.replace(/[^a-z]+/gi, '').split('');
console.log(onlyLettersArray)
Edit:
var myMessage = "Learning is fun!";
var arr1 = myMessage.split("");
function onlyLetters(array){
let arr2 = []
for(let i = 0; i < array.length; i++){
if(/[a-z]/.test(array[i])){ // you can use regex instead of all characters
arr2.push(array[i])
}
}
return arr2
}
console.log(onlyLetters(myMessage))
Update: If instead of an array of characters, you have to replace special chars in a string, you can write
let message = "Learning is fun!";
let letterMessage = message.replace(/[^a-zA-Z]/gm,"")
console.log(letterMessage)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With