Regex - Removing Dollar Sign From Text Input

Brds picture Brds · May 29, 2012 · Viewed 7.3k times · Source

I have a the following onkeyup command to test for, and remove, letters commas and dollar signs:

onkeyup="if (/(?:[a-zA-Z]|\s|,|\$)+/ig.test(this.value)) this.value = this.value.replace(/(?:[a-zA-Z]|\s|,|\$)+/ig,'')"

It works for everything except for the dollar signs.

Can anybody help me out here?

Thanks, Brds

Answer

agent-j picture agent-j · May 29, 2012

HTML interprets your backslash as escaping the inline html string, not the regex. The following code prints $.

<body onload='alert("\$");'> // prints '$', not '\$'

You need to escape twice, or move the regex out of the inline html and into a function.

I believe the correct answer is replace \$ with \\$, as follows:

onkeyup="if (/(?:[a-zA-Z]|\s|,|\\$)+/ig.test(this.value)) this.value = this.value.replace(/(?:[a-zA-Z]|\s|,|\$)+/ig,'')"