views:

79

answers:

2

I have a this regular expression below for some input name fields. How do I include an apostrophe and a hyphen in this?

InputField("tFName", /^[a-zA-Z-\-\ ]+$/);
+2  A: 

Hyphen is already included (twice), you can add the apostrophe by just editing it into the character class:

/^[a-zA-Z-\-\ ']+$/

You can rewrite it to look like this, so that theres no need for escaping the hyphen and it's only included once:

/^[a-zA-Z '-]+$/

Example: http://jsfiddle.net/a4vGA/

Andy E
Thanks I appreciate this
Moja Ra
I tried it like this: /^[a-zA-Z '-]+$/but I am still getting an error
Moja Ra
What's the error?
thenduks
could try `/^([a-zA-Z]|(\-*)|(\'*))+$/`
stocherilac
That did not work it escaped the hyphen but not the apostrophe.
Moja Ra
@Moja Ra not sure at what point you tried, I edited the regex so might want to take another look.
stocherilac
It is not allowing the apostrophe the way it is written /^([a-zA-Z]|(\-*)|(\'*))+$/
Moja Ra
I am able to escape the hyphen but I am still not able to escape the apostrophe in this regular expression for javascript.
Moja Ra
just another option... I'd try this myself but I dont have a way to test it on this computer at the moment. `/^([a-zA-Z]|(\-*)|['])+$/`
stocherilac
That did not work either.
Moja Ra
@Moja Ra alright, I'm sorry I wasn't able to help further. After I get home I will test some options and post back here if you don't have an answer yet.
stocherilac
Here is what I tried and it worked./^[a-zA-Z"'"]|(\-*)+$/
Moja Ra
@Moja: the regular expression I gave you works just fine - I added an example to my answer.
Andy E
A: 

Try this:

"abc'def ghi-jkl mno-pq'rst".match(/^[\w\s-']+$/)
  • \w for any letter
  • \s for space
  • - for hyphen
  • ' for apostrophe
Mic
`\s` will match more than just space - `\t\r\n`, among others, are also included. Also, `\w` will match `_`.
Andy E
@andy It is quite hard to get a \t\r\n in an input field but ok for the \w and _
Mic
@Mic: it's easier than you think, you'd be surprised how many people accidentally highlight an `\n` or `\r\n` when copy-pasting ;-) Although, that is what trimming is for.
Andy E
@andy Sure? I thought the \n\r were removed automatically from the value attribute of an INPUT.
Mic
@Mic: of course, you are right - it is still possible to paste a \t though ;-)
Andy E
@andy deuce! \r\n vs. \t_ but your rx is the right one!
Mic