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.

3
  • val.replace(/[^A-Za-z]/g,"") and jQuery is not part of this Commented Oct 15, 2020 at 11:02
  • I need to pass few special characters like * also. My point is to remove the invisible characters. Commented Oct 15, 2020 at 11:20
  • val.replace(/[^A-Za-z*]/g,"") - add the ones you want instead of the ones you do not want Commented Oct 15, 2020 at 11:21

2 Answers 2

1

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

str = str.replace(/[^a-zA-Z]/g, '');
Sign up to request clarification or add additional context in comments.

2 Comments

I need to pass few special characters like * also. My point is to remove the invisible characters.
Do you have a list of these special chars you want to allow?
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);

3 Comments

How is this different to my answer?
I can look at the times, your comment says 3min ago, my answer 4min ago
I'm not saying you copy-pasted it, but it's still the same answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.