简体   繁体   中英

Javascript Regex - replacing characters based on regex rules

I am trying to remove illegal characters from a user input on a browser input field.

const myInput = '46432e66Sc'
var myPattern = new RegExp(/^[a-z][a-z0-9]*/);
var test = myPattern.test(myInput);
if (test === true) {
 console.log('success',myInput)
} else {
  console.log("fail",myInput.replace(???, ""))
}

I can test with the right regex and it works just fine. Now I am trying to remove the illegal characters. The rules are, only lower case alpha character in the first position. All remaining positions can only have lower case alpha and numbers 0-9. No spaces or special characters. I am not sure what pattern to use on the replace line.

Thanks for any help you can provide.

Brad

You could try the below code:

const myInput = '46432e66Sc'
var myPattern = new RegExp(/^[a-z][a-z0-9]*/);
var test = myPattern.test(myInput);
if (test === true) {
  console.log('success',myInput)
} else {
  console.log("fail",myInput.replace(/[^a-z0-9]/g, ""))
}

Replace is using the following regexp: /[^a-z0-9]/g . This matches all characters that are not lowercase or numeric.

You can validate your regexp and get help from cheatsheet on the following page: https://regexr.com/

You could handle this by first stripping off any leading characters which would cause the input to fail. Then do a second cleanup on the remaining characters:

 var inputs = ['abc123', '46432e66Sc']; inputs.forEach(i => console.log(i + " => " + i.replace(/^[^az]+/, "").replace(/[^a-z0-9]+/g, "")));

Note that after we have stripped off as many characters as necessary for the input to start with a lowercase, the replacement to remove non lowercase/non digits won't affect that first character, so we can just do a blanket replacement on the entire string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM