Javascript regex to check if first and last characters are alike?

Is there an easy way to check if the first and last characters of a string are the same or not, only with a regular expression?

I know you can check with charAt

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

I do not ask for this: Regular expression to match the first and last character

+4
source share
1 answer

You can use a regular expression with a capture and backreference group to make the start and end characters the same, capturing the first kaharik. To check if the regular expression matches, use the method RegExp#test.

var regex = /^(.).*\1$/;

console.log(
  regex.test('abcdsa')
)
console.log(
  regex.test('abcdsaasaw')
)
Run codeHide result

Regex explanation here:

  • ^
  • 1- (.)
  • .* ( ) - , , ()
  • \1 ,
  • $

. , .

var regex = /^([\s\S])[\s\S]*\1$/;

console.log(
  regex.test(`abcd

sa`)
)
console.log(
  regex.test(`ab
c
dsaasaw`)
)
Hide result

: JavaScript ?

Regex :

  • [.....] - ,
  • \s - ( [\r\n\t\f\v ])
  • \s - ( [^\r\n\t\f ])

finally [\s\S] .

+8

Source: https://habr.com/ru/post/1667863/


All Articles