I have a the following onkeyup mand to test for, and remove, letters mas 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
I have a the following onkeyup mand to test for, and remove, letters mas 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
Share Improve this question edited May 29, 2012 at 16:25 agent-j 28k5 gold badges54 silver badges81 bronze badges asked May 29, 2012 at 16:10 BrdsBrds 1,0764 gold badges18 silver badges39 bronze badges 5-
4
This actually seems to work correctly for me as it is., but the regex can be much simpler:
/[a-z\s,$]/ig
unless I misunderstand you. jsfiddle/skM5N/3 – Michael Berkowski Commented May 29, 2012 at 16:16 -
Works for me... Try dumping
this.value
to the console and seeing what's there. – Alexander Pavlov Commented May 29, 2012 at 16:18 - It would probaby be less expensive to just run the replace without the test. – Daren Schwenke Commented May 29, 2012 at 16:18
- Looks like it's working to me: jsfiddle/wb4zG – aquinas Commented May 29, 2012 at 16:19
-
@Michael: also, the preliminary
if (...)
check is not necessary... – Alexander Pavlov Commented May 29, 2012 at 16:19
2 Answers
Reset to default 3If you are trying to clean up an arbitrary string into just a number, you'll chase less edge cases by replacing everything that isn't a digit (assuming you want an integer) with the empty string.
this.value = this.value.replace( /[^0-9]/, '' );
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,'')"