Regex - Javascript

  • Basic
    • variable =/value/ => Regular expression
    • /value/g => Make it global, Functions run for all matched values
    • /value/i => Makes it cases insensitive
    • variable.source => Returns var
    • variable.exec(S) => Returns the matched value, index, input, length as an object
    • variable.test(S) => Returns boolean value true if value is present
    • S.match(variable) => Returns array of values matched or null
    • S.search(variable) => Returns index of first match else -1
    • S.replace(variable, "value") => Returns new string with replaced values
  • Meta-characters
    • $, ^, ., *, ?, +, *, /, ., +
  • Character Sets
    • /va[abc]ue/ => Match if in place of l it contains a, b, c
    • /va[a-z]ue/ => Match if in place of l it contains a to z
    • /va[^abc]ue/ => Match if in place of l it does not contains a, b, c
    • /va[0-9]ue/
    • /va[A-Z]ue/
    • /[a-z]a[0-9]u[A-Z]/ => We can add many Character sets
    • Quantifiers
      • /val{n}ue/ => Match if l comes exactly n times
      • /val{n1,n2}ue/ => Match if l comes n1 to n2 times
    • Groupings
      • /(val){2}ue/ => Match if val comes 2 times
  • Character Classes
    • /va\wue/ => Matches if in place of l we have [A-Za-z0-9_], \W for opposite
    • /va\due/ => Matches if in place of l we have [0-9_], \D for opposite
    • /va\sue/ => Matches if in place of l we have [^ \t\r\n\f\v], \S for opposite, \b for word boundary
  • Assertion
    • /v(?=a)lue/ => Match only if a is after v
    • /v(?!a)lue/ => Match only if a not after v
Share: