简体   繁体   中英

javascript regex to check if first and last character are similar?

Is there any simple way to check if first and last character of a string are the same or not, only with regex?

I know you can check with charAt

var firstChar = str.charAt(0);
var lastChar = str.charAt(length-1);
console.log(firstChar===lastChar):

I'm not asking for this: Regular Expression to match first and last character

You can use regex with capturing group and its backreference to assert both starting and ending characters are same by capturing the first caharacter. To test the regex match use RegExp#test method.

 var regex = /^(.).*\\1$/; console.log( regex.test('abcdsa') ) console.log( regex.test('abcdsaasaw') )

Regex explanation here :

  1. ^ asserts position at start of the string
  2. 1st Capturing Group (.)
  3. .* matches any character (except newline) - between zero and unlimited times, as many times as possible, giving back as needed (greedy)
  4. \\1 matches the same text as most recently matched by the 1st capturing group
  5. $ asserts position at the end of the string

The . doesn't include newline character, in order include newline update the regex.

 var regex = /^([\\s\\S])[\\s\\S]*\\1$/; console.log( regex.test(`abcd sa`) ) console.log( regex.test(`ab c dsaasaw`) )

Refer : How to use JavaScript regex over multiple lines?

Regex explanation here :

  1. [.....] - Match a single character present
  2. \\s - matches any whitespace character (equal to [\\r\\n\\t\\f\\v ] )
  3. \\S - matches any non-whitespace character (equal to [^\\r\\n\\t\\f ] )

finally [\\s\\S] is matches any character.

You can try it

 const rg = /^([\w\W]+)[\w\W]*\1$/; console.log( rg.test(`abcda`) ) console.log( rg.test(`aebcdae`) ) console.log( rg.test(`aebcdac`) )

    var rg = /^([a|b])([a|b]+)\1$|^[a|b]$/;

    console.log(rg.test('aabbaa'))

    console.log(rg.test('a'))

    console.log(rg.test('b'))

    console.log(rg.test('bab'))

    console.log(rg.test('baba'))

This will make sure that characters are none other than a and b which have the same start and end.

It will also match single characters because they too start and end with same character.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM