简体   繁体   English

Javascript 正则表达式 - 根据正则表达式规则替换字符

[英]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.规则是,第一个 position 中只有小写字母字符。 All remaining positions can only have lower case alpha and numbers 0-9.所有剩余位置只能有小写字母和数字 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 .替换使用以下正则表达式: /[^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/您可以验证您的正则表达式并从以下页面上的备忘单获得帮助: 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.请注意,在我们删除了以小写开头的输入所需的尽可能多的字符之后,删除非小写/非数字的替换不会影响第一个字符,因此我们可以对整个字符串进行全面替换.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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