regular expression start and end with same character javascript

Regular Expression Start and End with Same Character JavaScript

Regular expressions, also known as regex or regexp, are patterns used to match character combinations in strings. In JavaScript, we can create regular expressions using the RegExp constructor or by using a regex literal enclosed in forward slashes (/regex/).

If you want to match a string that starts and ends with the same character, you can use a backreference in your regular expression.

Method 1: Using a Backreference

A backreference allows us to match a previously matched group. In this case, we want to match a string that starts and ends with the same character. We can use a capturing group to match the first character, then use a backreference to match the same character at the end of the string.


      const regex = /^([a-z])\w*\1$/;

      console.log(regex.test("anna")); // true
      console.log(regex.test("apple")); // false
    

In the above example, we are using the ^ and $ anchors to match the beginning and end of the string, respectively. The ([a-z]) capturing group matches any lowercase letter at the start of the string. The \w* quantifier matches zero or more word characters (letters, digits, or underscores). Finally, the \1 backreference matches the same character as the one matched by the first capturing group.

Method 2: Using Lookahead

We can also use a positive lookahead to match a string that starts and ends with the same character. A positive lookahead is a non-capturing group that matches a pattern without including it in the overall match.


      const regex = /^(?=\w*(\w)\w*$)\1/;

      console.log(regex.test("anna")); // true
      console.log(regex.test("apple")); // false
    

In the above example, we are using the ^ anchor to match the beginning of the string. The positive lookahead (?=\w*(\w)\w*$) matches any number of word characters followed by a capturing group that matches any character (\w) at the end of the string. Finally, the \1 backreference matches the same character as the one matched by the first capturing group.

Wrapping Up

Both of these methods will match strings that start and end with the same character. Which one you use will depend on your personal preference and the specific requirements of your project.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe