写个方法找出页面中除了数字和英文字母外的所有特殊特号

在前端开发中,如果你想找出一个字符串中除了数字和英文字母外的所有特殊字符,你可以使用正则表达式。以下是一个JavaScript函数的示例,该函数可以实现这个功能:

function findSpecialCharacters(str) {
    // 使用正则表达式匹配除了数字和英文字母外的所有字符
    const regex = /[^a-zA-Z0-9]/g;
    const matches = str.match(regex);
    
    // 去除重复的特殊字符并返回
    return [...new Set(matches)].filter(char => char !== undefined && char !== null);
}

// 示例使用
const text = "Hello, World! 123. This is a test. #SpecialChar";
const specialChars = findSpecialCharacters(text);
console.log(specialChars); // 输出: [ ',', '!', '.', ' ', '#' ]

这个函数使用正则表达式 /[^a-zA-Z0-9]/g 来匹配除了英文字母(大小写)和数字之外的所有字符。match() 方法用于检索字符串中与正则表达式匹配的所有子串,并返回一个数组。然后,我们使用 Set 对象去除数组中的重复项,并通过 filter() 方法去除 undefinednull 值。最后,我们得到一个包含所有特殊字符的数组。

posted @ 2024-12-17 09:03  王铁柱6  阅读(19)  评论(0)    收藏  举报