Hoa
Hoa

Reputation: 20438

How can I write a JavaScript regular expression to allow only letters and numbers?

I wish to allow both upper case and lower case. I have tried

'k abBcdi #!129'.replace(/^[A-Za-z0-9]/g,'')

But it's not give me the correct answer

Upvotes: 1

Views: 261

Answers (3)

David Thomas
David Thomas

Reputation: 253308

If you don't explicitly need to use the not ^ operator, you could simply use a special character to identify all non-alphanumeric characters:

'k abBcdi #!129'.replace(/[\W]/g,'')

Or, given that \W allows the underscore (_) it might be preferred to use:

'k abBcdi #!129'.replace(/(\W+)|(_)/g,'')

References:

Upvotes: 0

Frank B
Frank B

Reputation: 658

Also use [^0-9A-z] instead. It probably has little to no performance effect, but it is slightly shorter and prettier.

Edit:Per a comment above, are you trying to find all letters and numbers and replace them or remove everything that's not a letter and number?

Upvotes: 3

antyrat
antyrat

Reputation: 27765

You need to use NOT operator (^) inside brackets:

/[^A-Za-z0-9]/g

Upvotes: 5

Related Questions