如何动态检测字符串中的连字符/@并提取分隔姓名到数组?
动态提取姓名的解决方案
可以用正则表达式配合split()或match()方法实现,不管分隔符是-还是@都能处理,同时兼容分隔符前后的空格:
方法1:split() + 过滤分隔符
通过正则匹配两种分隔符(包含前后可能的空格),再过滤掉数组中的分隔符元素:
// 示例字符串 const strWithDash = "bill - nick"; const strWithAt = "bill @ nick"; // 正则匹配:任意空格 + (-或@) + 任意空格 const separatorRegex = /\s*([-@])\s*/; // 分割后过滤掉分隔符 const namesFromDash = strWithDash.split(separatorRegex).filter(item => !['-', '@'].includes(item)); const namesFromAt = strWithAt.split(separatorRegex).filter(item => !['-', '@'].includes(item)); console.log(namesFromDash); // 输出: ["bill", "nick"] console.log(namesFromAt); // 输出: ["bill", "nick"]
方法2:match()直接提取姓名
用正则匹配所有非分隔符、非空格的连续字符,直接得到姓名数组:
const nameRegex = /[^\s-@]+/g; const names1 = strWithDash.match(nameRegex); const names2 = strWithAt.match(nameRegex); console.log(names1); // 输出: ["bill", "nick"] console.log(names2); // 输出: ["bill", "nick"]
如果之后需要支持更多分隔符,只需要修改正则里的[-@]部分,比如要加|就改成[-@|],非常灵活。
内容的提问来源于stack exchange,提问作者vasilis 123
相关产品推荐
相关产品推荐

