简体   繁体   中英

Regex - Removing Dollar Sign From Text Input

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

如果您尝试将任意字符串清理成一个数字,则可以通过用空字符串替换非数字的所有内容(假设您想要一个整数)来减少边缘情况。

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM