Home > database >  Javascript Regex - replacing characters based on regex rules
Javascript Regex - replacing characters based on regex rules

Time:01-12

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

CodePudding user response:

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/

CodePudding user response:

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(/^[^a-z] /, "")
                                              .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.

  •  Tags:  
  • Related