Skip to content Skip to sidebar Skip to footer

Javascript Replace With Regex Not Working Correctly

I'm trying to validate a name with regex, the regex stops the user from entering 2 spaces or dots in a row. This is my code: At the moment I want to enter a letter, I cant I don'

Solution 1:

With this solution it deletes only the second space or second dot and the first ones will still remain:

functiontest(input){
  var regex=/\.(?=\.)|\s(?=\s)/;
  input.value = input.value.replace(regex, "");
}
<inputid="txt_NomCandidato"onkeyup="test(this);"type="text"class="form-control"name="txt_Nom">

Solution 2:

The following regex should work for you: /[^a-zA-Z. ]|\.(?=\.)|\s(?=\s)/g

  • [^a-zA-Z. ]+ Limits all allowed characters to a-z, A-Z, dots, or spaces
  • \.(?=\.) Limits it to only allow one dot in a row
  • \s(?=\s) Limits it to only one space in a row

Each of these are separated by | (the or condition)

functiontest(input) {
  var regex = /[^a-zA-Z. ]|\.(?=\.)|\s(?=\s)/g;
  input.value = input.value.replace(regex, "");
}
<inputid="txt_NomCandidato"onkeyup="test(this);"type="text"class="form-control"name="txt_Nom">

Solution 3:

Your regex seems correct (it matches any string with no more than 1 space or 1 dot together), but your the logic in your function seems wrong.

What it's doing: anytime the value changes, take the value and replace anything that matches that regex with an empty string, so any time you write a character its replaced (because it matches the regex).

I would go with one of this options:

a) show a message if the value doesn't match the regex

b) change the regex to /.{2}| {2}/ and only replace the two dots or the two spaces, as Scath says in another answer

c) maybe just using the input pattern attribute with your original regex is enough: https://www.w3schools.com/TAGS/att_input_pattern.asp

Hope this helps!

Solution 4:

To achieve expected result, use below option of slice

input.value.slice(-2) will return last two entered characters and if it is ".." or " "(double spaces) replace it with ''

functiontest(input){
  if(input.value.slice(-2)=='..' || input.value.slice(-2)=='  '){
         input.value = input.value.replace(input.value.slice(-2), "");
     }
}
<inputid="txt_NomCandidato"onkeyup="test(this);"type="text"class="form-control"name="txt_Nom">

code sample - https://codepen.io/nagasai/pen/VXNOej

Your regex clears any characters starts with [A-Z] or [a-z] due to expression ^[A-Za-z]

Solution 5:

This regex will not allow them to enter two periods or two spaces, when they enter the second of either it will clear.

functiontest(input){
  var regex=/\.{2}| {2}/;
  input.value = input.value.replace(regex, "").replace(/\d+|/g, '').replace(/\s+/g, ' ').replace(/[^\w]/, '');
}
<inputid="txt_NomCandidato"onkeyup="test(this);"type="text"class="form-control"name="txt_Nom">

Post a Comment for "Javascript Replace With Regex Not Working Correctly"