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.

Share:
15,287

Related videos on Youtube

Mosh Feu
Author by

Mosh Feu

SOreadytohelp DM Linkedin Twitter Slack Links My Story blog medium

Updated on September 16, 2022

Comments

  • Mosh Feu
    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
    Naveed S over 11 years
    @mosh In which part do you want to include '? Is it like the sample I gave?
  • ZagNut
    ZagNut about 9 years
    downvoted. question is for javascript. you must escape the single quote.
  • Aaron
    Aaron over 6 years
    The 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
    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 the RegExp("pattern", flags) constructor, in both case because they delimit the pattern.
  • Aaron
    Aaron over 6 years
    Err, 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.