0

I have the following regular expression

/[^a-zA-Z0-9 ]/g

I want include " in the following piece of code:

onKeyUp="this.value=this.value.replace(/[^a-zA-Z0-9"]/g,'')

I used the above regex.

The problem I am facing over here is that the above regular expression allows me to include other special characters (&, *, etc.) into it. How do I avoid it?

2 Answers 2

2

Just put the characters into the character class while taking the correct encoding into account:

onKeyUp="this.value=this.value.replace(/[^a-zA-Z0-9"&*]/g,'')"

Here you need to encode " and & with the character references " and & as you’re describing the value of an HTML attribute value declaration.

Sign up to request clarification or add additional context in comments.

Comments

1

One first obvious issue with the code is that the " that is part of the regex isn't escaped despite it being inside a "-delimited string literal. You may want to try and change it to:

onKeyUp="this.value=this.value.replace(/[^a-zA-Z0-9\" ]/g,'')

2 Comments

Yep, I realized a bit afterwards I wasn't actually answering your question, but just fixing an obvious issue that could have been a blocker to resolution. @Gumbo's answer is a proper one, especially in that context.
Well I have it working in several context (MS RegEx, Perl, ...=, but I'd effectively think it probably won't work in the context of JavaScript's work on HTML stuff.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.