0

I am performing a validation in html text box which should pass only alphabets(a-z/A-Z) and few special characters like (*,& etc..). Otherwise it should show error some error. I had written a JavaScript function which does the same.

function removeInvalidCharacters(selectedElement) {
    if (selectedElement && typeof selectedElement.val() !== typeof undefined && selectedElement.val() != "") {
        selectedElement.val(selectedElement.val().replace(/[\u0000-\u001F]|[\u007F-\u00A0]/g, "").replace(/\\f/g, "").replace(/%/g,""));
    }
}

I am filtering selectedElement before passing to the function removeInvalidCharacters.

$("#name").val(toASCII($("#name").val()));
var selectedElement = $("#name").val();

But now I am facing a scenario in which empty characters, blank characters, invisible characters and whitespace characters are bypassing my regex. I could see some invisible characters are present in my name field. I want to replace these characters.

In further investigation I could found that Invisible characters - ASCII characters mentioned in this link are the culprits. I need to have a regex to catch them and replace them.

Eg: AAAAAAAAAAAA‎AAAAAAAAAAA is the value in text field. Now if we check $("#name").val().length, it gives 24 ,even though we could see only 23 characters. I need to remove that hidden character.

Please help me with this scenario. Hope my query is clear

UPDATE:

var result = selectedElement.replace(/[\u200B-\u200D\uFEFF]/g, ''); fixed my problem. Thank you all for the support.

Jince Martin
  • 211
  • 1
  • 3
  • 14

2 Answers2

1

If you want to allow only (a-z/A-Z) like you mention, try this:

str = str.replace(/[^a-zA-Z]/g, '');
domenikk
  • 1,723
  • 1
  • 10
  • 12
1

Include the chars you want to keep instead of the ones you do not want, since that list may be incomplete

Otherwise look here: Remove zero-width space characters from a JavaScript string

const val = `AAAAAAAAAAAA‎AAAA**AAAAAAA`;
const cleaned = val.replace(/[^A-Za-z*]/g,"");
console.log(val.length,cleaned.length);
mplungjan
  • 169,008
  • 28
  • 173
  • 236