RegEx for Javascript to allow only alphanumeric

前端 未结 18 1526
轻奢々
轻奢々 2020-11-22 15:13

I need to find a reg ex that only allows alphanumeric. So far, everyone I try only works if the string is alphanumeric, meaning contains both a letter and a number. I just w

18条回答
  •  情书的邮戳
    2020-11-22 15:35

    Save this constant

    const letters = /^[a-zA-Z0-9]+$/
    

    now, for checking part use .match()

    const string = 'Hey there...' // get string from a keyup listner
    let id = ''
    // iterate through each letters
    for (var i = 0; i < string.length; i++) {
      if (string[i].match(letters) ) {
        id += string[i]
      } else {
        // In case you want to replace with something else
        id += '-'  
      }
    }
    return id
    

提交回复
热议问题