If you have searched many websites to learn Regular expressions but still searching for a better tutorial than you are at the right place.

Regular Expression

also known as Regex are a little difficult to write but actually once you have learn how to use few symbols and modifiers you can create your own javascript Regular expressions and can save your time and code length.

What you can do with Javascript Regular Expression

  • Search for a pattern
  • Search for particular characters
  • Replace particular characters or words from a string

  • Introduction to symbols

    [abc] Search for any character which is within the brackets.
    [^abc] Search for any character which is not within the brackets.
    [0-9] Search for any digit from 0 to 9.
    [A-Z] Search for any character from capital A to capital Z.
    [a-z] Search for any character from lowercase a to lowercase z.
    [A-z] Search for any character from capital A to lowercase z.
    [scfl] Search any character which is in the given set.
    [^adgk] Search any character which is not in the given set.

    ^ Matches the position at the beginning of the input string.
    $ Matches the position at the end of the input string.
    * Matches the preceding subexpression zero or more times.
    + Matches the preceding subexpression one or more times.
    ? Matches the preceding subexpression zero or one time.
    {n} Matches exactly n times, where n is a nonnegative integer.
    {n,} Matches at least n times, n is a nonnegative integer.
    {n,m} Matches at least n and at most m times, where m and n are nonnegative integers and n <= m.

    Modifiers

    i Perform case-insensitive matching
    g Perform a global match (Search all matches rather than stopping after the first match)
    m Perform multiline matching

    Searching for a pattern through Javascript Regular Expression

    You can search for any pattern by using the function search(pattern).
    Example:-
    var str=”this is a Testing string”;
    var result= str.search(/test/i);
    document.write(result);

    This will print:-
    10

    Replacing for a pattern through Javascript Regular Expression

    You can replace any pattern by using the function replace(pattern,string_to_replace_with).
    Example:-
    var str=”this is a Test string. this is second test.”;
    var result= str.replace(/test/ig,”new”);
    document.write(result);

    This will print:-
    this is a new string. this is second new.

    One Response so far.

    1. Susan says:

      Much appreciated for the information and share!