Search This Blog

2024/04/05

Javascript Regular Expression:Check char repeated & consecutive

How to check in given string atleast one character is repeated and
they are consecutive?

Code:
function hasSameConsecutiveChars(str){
let pattern = /([A-Za-z0-9])\1/gmi
return pattern.test(str);
}

console.log('does string "bheem" has same consecutive characters:',hasSameConsecutiveChars('bheem'))
console.log('does string "raja" has same consecutive characters:',hasSameConsecutiveChars('raja'))
console.log('does number "888786" has same consecutive characters:',hasSameConsecutiveChars('888'))
console.log('does string "india2022" has same consecutive characters:',hasSameConsecutiveChars('india2022'))
console.log('does string "bosS" has same consecutive characters:',hasSameConsecutiveChars('bosS'))
Output:
does string "bheem" has same consecutive characters: true
does string "raja" has same consecutive characters: false
does number "888786" has same consecutive characters: true
does string "india2022" has same consecutive characters: true
does string "bosS" has same consecutive characters: true

No comments:

Post a Comment