最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Regex - Removing Dollar Sign From Text Input - Stack Overflow

programmeradmin2浏览0评论

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
Add a ment  | 

2 Answers 2

Reset to default 3

If 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,'')"
发布评论

评论列表(0)

  1. 暂无评论