[Webinar] Learn how to a build a cloud-first strategyRegister Now

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 929
  • Last Modified:

regEx to allow A-Z and single spaces only?

I am using a simple "onkeyup" with a regEx to replace anything but letters as the user types into a small text input. Works great... but I need to modify it so that *single* spaces are allowed.

Currently the code looks like this
<input type="text" size="12" maxlength="12" name="pfWord" id="pfWord"
onkeyup="this.value=this.value.replace(/[^a-z]/ig, '')">

How should I alter the regEx to also say
"allow spaces AND letter a-z"
"replace more than one space with a single space"
1 Solution
onkeyup="this.value=this.value.replace(/[^a-z][\s]{1,1}/ig, '')"
ZvonkoSystems architectCommented:
Check this:

<input type="text" size="12" maxlength="12" name="pfWord" id="pfWord"
onkeyup="if(!this.value.match(/^([a-z]+\s?)*$/i))this.value=this.value.replace(/[^a-z ]/ig,'').replace(/\s+/g,' ')" >

MichaelEvangelistaAuthor Commented:
PERFECT Zvonko, thank you!

Mr_Egyptian: this worked, except double spaces were removed rather than replaced with a single space.

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now