如何过滤字符串以仅包含香草Javascript中的字母? [英] How do I filter out a string to contain only letters in vanilla Javascript?

查看:66
本文介绍了如何过滤字符串以仅包含香草Javascript中的字母?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到了这个字符串:

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))

我做错了什么?另外,有列出字母"a"到"z"的简写吗?

What am I doing wrong? Also, is there a shorthand for listing letters "a" through "z"?

推荐答案

一种简单的方法可能是像这样使用Regex

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接受一个数组并在元素上运行一个函数,该函数返回true或false.如果该项目返回false,则将其删除.正则表达式检查字符是否在a-z或A-Z范围内

.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)

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)


这篇关于如何过滤字符串以仅包含香草Javascript中的字母?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆