views:

49

answers:

2

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 charaters (&, *, etc.) into it. How do I avoid it???

+1  A: 

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,'')

Romain
i tried this but it did not work
manugupt1
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.
Romain
Using a plain `"` inside the attribute value won’t work.
Gumbo
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.
Romain
+2  A: 

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.

Gumbo