js操作字符串

z333 sb666 z h333 返回false
z555 sb888 x666 返回true
z555 sb888()()x666 返回true(两个空格)

匹配字符串必须是字母+数字

阅读 1.9k
2 个回答
function test(str) {
    if (typeof str !== "string") return false;
    return str.split(/\s+/).every(n => /^[a-z]+\d+/i.test(n));
}
test("z333 sb666 z h333");

将字符串按照空格进行拆分,对每一段进行校验即可,只要其中一个不满足,那么整段字符串就不满足要求

function hasLetterAndNum(str) {
    return str.split(/\s+/).every(item => /^(?=.*?[0-9])(?=.*?[a-z])[0-9a-z]+$/.test(item))
}

测试:

hasLetterAndNum('qwerty') // false
hasLetterAndNum('123456') // false
hasLetterAndNum('qwe123') // true
hasLetterAndNum('qwe123 qwe abc46') // false
hasLetterAndNum('qwe123 5566 abc46') // false
hasLetterAndNum('qwe123 5566c abc46') // true
hasLetterAndNum('qwe123 5566c     abc46') // true
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题