Javascript regular expression single quotes
15,287
Solution 1
You can use the following regex for example to allow a string like abcd'dfgh
:
/^[A-Za-z\/\']+[A-Za-z]$/
Solution 2
To allow single quote, add it in the character class like ^[a-z A-Z._']{1,15}$
This regex allows '
matching 'abc'_
, a'b'c_
etc.
Related videos on Youtube
Author by
Mosh Feu
SOreadytohelp DM Linkedin Twitter Slack Links My Story blog medium
Updated on September 16, 2022Comments
-
Mosh Feu over 1 year
My Regex is:
var re = /^[a-z A-Z._]{1,15}$/;
I want to allow this:
'
(Single Quote).How can I do this?
-
Naveed S over 11 years@mosh In which part do you want to include
'
? Is it like the sample I gave? -
ZagNut about 9 yearsdownvoted. question is for javascript. you must escape the single quote.
-
Aaron over 6 yearsThe regex now accepts slashes, doesn't accept spaces underscores nor dots anymore, doesn't validate that the string is 15 chars at most and now require the string to be 2 chars at least. Also
'
won't be matched if it is the last char. Why the hell was this accepted and upvoted to +4? -
Aaron over 6 years@ZagNut that is incorrect. Here's an example of a regex replace where the regex contains unescaped single quotes. Aside from regex meta-characters, in JS only forward slashes need to be delimited if you're using the
/pattern/flags
construct, or double quotes if you're using theRegExp("pattern", flags)
constructor, in both case because they delimit the pattern. -
Aaron over 6 yearsErr, I should be careful not to make mistakes when correcting others... Since strings can be represented enclosed in single-quotes in JS, you can use
new RegExp('pattern', flags)
to create regexs, in which case single-quotes should be escaped in the pattern (example). This is to my knowledge the only case where it makes sense to escape single quotes in JS regex.